Java Xpath具有父节点相同名称的多个元素

时间:2016-10-26 07:07:10

标签: java xml xpath

我有一个像下面的xml。

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

现在使用java的Xpath查询我尝试了下面的方法

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

但它只给我第一个值,如何打印所有<value>标签?

1 个答案:

答案 0 :(得分:1)

您的XPath表达式是正确的,您的代码中很可能存在其他问题。你真的应该提供一个证明你问题的完整例子。

以下代码演示了这种情况:

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

}

运行此结果会产生以下输出:

value
value
value