Home > Net >  How to loop all elements that match the same xPath - Java
How to loop all elements that match the same xPath - Java

Time:06-13

Hi all I have something like the following xml:

<something>
 <fruit>
 <colour>red</colour>
 </fruit>
 <fruit>
 <colour>blue</colour>
 </fruit>
 <fruit>
 <colour>green</colour>
 </fruit>
</something>

and currently I access the node value like so:

XPath xPath = XPathFactory.newInstance().newXPath();
String nodeValue = (String) xPath.evaluate("something/fruit/colour", xmlDocument, XPathConstants.STRING);

I am wondering how I can make it so that I loop through each matching path?

so something like:

foreach matching path  {
// Print value of that path 
}

CodePudding user response:

Use this article to help.

Below I have created a small working example, with fruits.xml holding your XML example.

    FileInputStream fileIS = new FileInputStream(new File("fruits.xml"));
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(fileIS);
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/something/fruit/colour";
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i  ) {
        Node node = nodeList.item(i);
        System.out.print(node.getTextContent());
    }

This will produce:

red blue green

  • Related