获取DOM子树的所有属性的Xpath?

时间:2011-08-27 17:37:02

标签: java dom xpath

有人可以解释为什么会这样吗?以下是我得到的代码:

String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<title text=\"title1\">\n" +
"    <comment id=\"comment1\">\n" +
"        <data> abcd </data>\n" +
"        <data> efgh </data>\n" +
"    </comment>\n" +
"    <comment id=\"comment2\">\n" +
"        <data> ijkl </data>\n" +
"        <data> mnop </data>\n" +
"        <data> qrst </data>\n" +
"    </comment>\n" +
"</title>\n";

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
NodeList nlist = doc.getElementsByTagName("comment");

XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
NodeList nodes = (NodeList)xp.evaluate("//@*", nlist.item(0), XPathConstants.NODESET);
for(int i = 0; i < nodes.getLength(); i++)
    System.out.println(nodes.item(i));

产生的输出是:

text="title1"
id="comment1"
id="comment2"

问题是,我正在尝试对子树(即第一个comment块)执行XPath查询,所以我只想获得此子树的所有属性但由于某种原因,无论我传入哪个子树,它总是返回所有属性节点,就像传递给xpath求值程序的对象是根节点一样。

如何传入并评估子树的所有属性

1 个答案:

答案 0 :(得分:2)

您必须从XPath表达式中省略//。

NodeList nodes = (NodeList)xp.evaluate("@*", nlist.item(0), XPathConstants.NODESET);