在java中以XML显示文本内容

在java中以XML显示文本内容,java,xml,Java,Xml,您将获得方法中的值。你基本上要做到以下几点 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { tempVal = ""; if(qName.equalsIgnoreCase("iata:Airline")) { //create a new inst

您将获得方法中的值。你基本上要做到以下几点

public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                tempVal = "";
        if(qName.equalsIgnoreCase("iata:Airline")) {
            //create a new instance of employee
            tempEmp = new employee();
            tempEmp.setType(attributes.getValue("CodeContext"));
            }

使用SAX很麻烦。我建议使用DOM。但话说回来,他们有自己的优势和劣势。DOM更容易编码,但通常比SAX更慢、内存更昂贵。

首先使用XML的模式文件加载XML文档

boolean isDepartureAirportElement = false;
StringBuffer value = new StringBuffer();

void startElement(...) {
    if (qName.equals("iata:DepartureAirport")) {
        isDepartureAirportElement = true; // set true when your element started 
        String codeContext = attributes.getValue("CodeContext")
    }
}

void characters(char[] buffer, int start, int length) {
    if (isDepartureAirportElement) {
        value.append(buffer, start, length);
    }
}

void endElement(...) {
    if (qName.equals("iata:DepartureAirport")) {
        isDepartureAirportElement = false; // set false when your element ends
    }
}
将xml转换为文档格式后,可以使用此方法获取特定节点

/**
     * This method reads in the xmlFile, validates it against the
     * schemaFile, and if valid, loads it into a WhitespaceFreeXMLDoc
     * and returns it, which helps because that's a much easier
     * format for us to deal with.
     * 
     * @param xmlFile Path and name of xml file to load.
     * 
     * @param schemaFile Path and name of schema file to use for validation.
     * 
     * @return A normalized Document object fully loaded with the data found
     * in the xmlFile.
     * 
     * @throws InvalidXMLFileFormatException Thrown if the xml file validation fails.

     */
    public Document loadXMLDocument(String xmlFile, String xsdFile)
            throws InvalidXMLFileFormatException
    {
        // FIRST VALIDATE
        boolean isValid = validateXMLDoc(xmlFile, xsdFile);
        if (!isValid)
        {
            throw new InvalidXMLFileFormatException(xmlFile, xsdFile);
        }

        // THIS IS JAVA API STUFF
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try
        {            
            // FIRST RETRIEVE AND LOAD THE FILE INTO A TREE
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document xmlDoc = db.parse(xmlFile);
            xmlDoc.getDocumentElement().normalize();

            // LET'S RETURN THE DOC
            return xmlDoc;
        }
        // THESE ARE XML-RELATED ERRORS THAT COULD HAPPEN DURING
        // LOADING AND PARSING IF THE XML FILE IS NOT WELL FORMED
        // OR IS NOW WHERE AND WHAT WE SAY IT IS
        catch(ParserConfigurationException | SAXException | IOException pce)
        {
            throw new InvalidXMLFileFormatException(xmlFile);
        }           
    } 
如果要获取节点本身,而不是BOM表中的节点中的数据

 /**
     * This method extracts the data found in the doc argument that 
     * corresponds to the tagName and returns it as text. If no data
     * is found, null is returned. Note that this method is only good 
     * for elements that are unique to an XML file, meaning there is only 
     * one of them.
     * 
     * @param doc Fully-loaded DOM Document corresponding to a loaded
     * XML file from which we are loading the data.
     * 
     * @param tagName Name of the tag (i.e. field name) we are looking
     * to load data for.
     * 
     * @return The data in the doc that corresponds to the tagName element.
     * Note that if no data is found, null is returned.
     */
    public String getTextData(Document doc, String tagName)
    {
        // IT WAS FOUND, SO GET THE DATA
        Node node = getNodeWithName(doc, tagName);
        if (node == null)
        {
            return null;
        }
        else
        {
            String data = node.getTextContent();
            return data;   
        }
    }
如果您还有任何问题,请告诉我

xml中的“9W”在哪里?
 /**
     * This method extracts the data found in the doc argument that 
     * corresponds to the tagName and returns it as text. If no data
     * is found, null is returned. Note that this method is only good 
     * for elements that are unique to an XML file, meaning there is only 
     * one of them.
     * 
     * @param doc Fully-loaded DOM Document corresponding to a loaded
     * XML file from which we are loading the data.
     * 
     * @param tagName Name of the tag (i.e. field name) we are looking
     * to load data for.
     * 
     * @return The data in the doc that corresponds to the tagName element.
     * Note that if no data is found, null is returned.
     */
    public String getTextData(Document doc, String tagName)
    {
        // IT WAS FOUND, SO GET THE DATA
        Node node = getNodeWithName(doc, tagName);
        if (node == null)
        {
            return null;
        }
        else
        {
            String data = node.getTextContent();
            return data;   
        }
    }
 /**
     * This method can be used to get the node in the document
     * that is an element of type tagName. null is returned
     * if none is found.
     * 
     * @param doc The XML document to search
     * 
     * @param tagName The name of the XML element/tag to
     * search for.
     * 
     * @return The first node found named tagName. If none is
     * found in the document, null is returned.
     */
    public Node getNodeWithName(Document doc, String tagName)
    {
         // GET THE NODE FOR THE tagName ELEMENT
        NodeList nodeList = doc.getElementsByTagName(tagName);

        // IF NOT FOUND, DON'T GO ON
        if (nodeList.getLength() == 0)
        {
            return null;
        }

        // IT WAS FOUND, SO GET THE DATA
        Node node = nodeList.item(0);
        return node;
    }