1

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

2
  • Please can you explain more about third level? Commented Mar 17, 2014 at 19:01
  • What i meant was the <value> child element under distance is at the third level from its root element <row>. Like i wanted to know can i directly access the distance element one after the other and fetch the value element. well that is what i have understood about DOM? Commented Mar 17, 2014 at 19:07

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well u r right. I can actually go for JaxB. But in my project the XML data is fixed
So if it is fix then go for Jaxb. Regardless of accepted answer. It is simply better imho.
1

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

Comments

0

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

1 Comment

I have updated my code to access value element present under distance element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.