Retrieve particular child node using xpath in java

427 Views Asked by At

I have xml like below

  <results>
        <result>
            <location>/tmp/path1</location>
            <name>name1</name>
        </result>
        <result>
            <location>/tmp/path2</location>
            <name>name2</name>
        </result>
    </results>

I want to iterate over all the result objects and use location and name from each. I'm using following code to get a list of result objects

XPathExpression expression = XPathFactory.newInstance().newXPath().compile("/results/result");
NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET); 
for (int i = 0; i < nodes.getLength(); i++) {
  Node node = nodes.item(i);
  // ??
}

How can I get value of location and name from node?

1

There are 1 best solutions below

0
queeg On

You can get the values for example like this. There are other possibilities as well. I did not optimize the code though.

XPathExpression expression = XPathFactory.newInstance().newXPath().compile("/results/result");
NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET); 
for (int i = 0; i < nodes.getLength(); i++) {
    Node node = nodes.item(i);
    String location = XPathFactory.newInstance().newXPath().evaluate("location", DomSource(node));
    String name = XPathFactory.newInstance().newXPath().evaluate("name", new DomSource(node));
}