简体   繁体   中英

Retrieve particular child node using xpath in java

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?

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));
}

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