serverliving.com serverliving.com - 1 month ago 11
Java Question

Java Xpath multiple elements with same name of a parent node

I have an xml like below.

<name>
<value>123</value>
<value>456</value>
<value>789</value>
</name>


Now using java's Xpath query I tried below method

NodeList list3 = (NodeList) xpath.evaluate("name/value", element,XPathConstants.NODESET);


But it gives me only first value, how can I print all
<value>
tags ?

Answer

Your XPath expression is correct, there is most likely another problem in your code. You really should provide a complete example which demonstrates your problem.

The following code demonstrates how this would look like:

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XmlTest {

    public static void main(String[] args) throws Exception {
        String xml = "<name>\n" +
                "<value>123</value>\n" +
                "<value>456</value>\n" +
                "<value>789</value>\n" +
                "</name>";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        NodeList list = (NodeList) xpath.evaluate("name/value", doc, XPathConstants.NODESET);

        for (int i = 0; i < list.getLength(); ++i) {
            Node node = list.item(i);
            System.out.println(node.getNodeName());
        }
    }

}

Running this results in the following output:

value
value
value