简体   繁体   中英

Parsing XML file In java using DOM

I want to parse XML file to read values of certain elements in the file.

<row>
<element>
 <status>OK</status>
<duration>
 <value>499</value>
 <text>8 mins</text>
 </duration>
 <distance>
 <value>3208</value>
 <text>3.2 km</text>
</distance>
</element>
<element>
 <status>OK</status>
 <duration>
 <value>501</value>
<text>8 mins</text>
 </duration>
<distance>
<value>2869</value>
<text>2.9 km</text>
</distance>
</element>
<element>
<status>OK</status>
<duration>
<value>788</value>
 <text>13 mins</text>
</duration>
<distance>
<value>6718</value>
<text>6.7 km</text>
</distance>
</element>
</row>

I want to able to read the values of all "value" tags under "distance" tags. I have done the basic code to read XML data. I just want the idea to read the value of elements at the third level

Simple DOM parsing is not the preferred way anymore IMHO. Java comes with some mature frameworks to makes the parsing life much more easier. The following is some kind of my preference. Others may think different.

  1. If the structure of your XML is fix, you could build some JAXB annotated pojos and read your data with this. JAXB delivers complete object hierarchies filled with your XML values. As well the XML data creation is also provided.

  2. If you dont know the structure of your XML data or you stream XML data then maybe STAX parsing is the way to go.

Anyway these frameworks take a lot of problems away from you like file encoding, syntax checking, type safety (JAXB), ....

If you want to use DOM parsing, then you could use XPath to shorten your requests dramatically:

XPath xPath =  XPathFactory.newInstance().newXPath();

InputSource source = new InputSource(ParseUsingXPath.class.getResourceAsStream("data.xml"));
NodeList list = (NodeList) xPath.evaluate("/row/element/distance/value", source, XPathConstants.NODESET);
for (int i=0;i<list.getLength();i++) {
    System.out.println(list.item(i).getTextContent());
}

and it outputs:

3208
2869
6718

Here I use your XML directly as a StringStream from a file. You could use XPath with an DOM document object as well to process global searches.

have you already used xsd definition of xml? With this and jaxb you can unmarshal the xml to a java object in easy way.

Below code might help you to access value element.

import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class DOMParsarDemo {
    protected DocumentBuilder docBuilder;
    protected Element root;

    public DOMParsarDemo() throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        docBuilder = dbf.newDocumentBuilder();
    }

    public void parse(String file) throws Exception {
        Document doc = docBuilder.parse(new FileInputStream(file));
        root = doc.getDocumentElement();
        System.out.println("root element is :" + root.getNodeName());
    }

    public void printAllElements() throws Exception {
        printElement(root);
    }

    public void printElement(Node node) {
        if (node.getNodeType() != Node.TEXT_NODE) {
            Node child = node.getFirstChild();
            while (child != null) {
                if (node.getNodeName().equals("distance")) {
                    if (child.getNodeName().equals("value")) {
                        System.out.println(child.getFirstChild().getNodeValue());
                    }
                }
                printElement(child);
                child = child.getNextSibling();
            }
        }
    }

    public static void main(String args[]) throws Exception {
        DOMParsarDemo demo = new DOMParsarDemo();
        demo.parse("resources/abc.xml");
        demo.printAllElements();
    }
}

output:

root element is :row
3208
2869
6718

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM