Xpath获取DOM子树的所有属性?
有人可以解释一下为什么会发生这种情况吗?以下是我得到的代码:
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 求值器中的是根节点。
我怎样才能传入并评估子树的所有属性?
Could someone please explain why this is happening; this following is the code I’ve got:
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));
The output produced is:
text="title1"
id="comment1"
id="comment2"
The problem is, I am trying to do an XPath query on a sub-tree (i.e. the first comment
block), so I just want to get all attributes for this sub-tree but for some reason, whichever sub-tree I pass in, it always returns all attribute nodes, as if the object being passed into the xpath evaluator is the root node.
How can I just pass in and evaluate all attributes for a subtree?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须从 XPath 表达式中省略 //。
You have to omit the // from the XPath expression.