如何使用 XPath 按 TextContent 过滤元素?通过轴获取父级? [英] How to use XPath to filter elements by TextContent? get parent by axis?
问题描述
我发现 关于 SO 的类似问题,但是,似乎不是我想要实现的目标:
I've found a similar question on SO, however, that seems not exactly what I wanna achieve:
比如说,这是一个示例 XML 文件:
Say, this is a sample XML file:
<root>
<item>
<id isInStock="true">10001</id>
<category>Loose Balloon</category>
</item>
<item>
<id isInStock="true">10001</id>
<category>Bouquet Balloon</category>
</item>
<item>
<id isInStock="true">10001</id>
<category>Loose Balloon</category>
</item>
</root>
如果我想得到一个过滤的"此 XML 中 item 元素的子集,我如何使用 XPath 表达式直接解决该问题?
If I wanna get a "filtered" subset of the item elements from this XML, how could I use an XPath expression to directly address that?
XPathExpression expr = xpath.compile("/root/item/category/text()");
我现在知道这将评估为类别中所有 TextContent 的集合,但是,这意味着我必须使用集合来存储值,然后迭代,然后返回获取其他相关信息,例如再次输入项目 ID.
I now know this would evaluate to be the collection of all the TextContent from the categories, however, that means I have to use a collection to store the values, then iterate, then go back to grab other related info such as the item id again.
另一个问题是:如何正确引用父节点?
Another question is : how could I refer to the parent node properly?
比如说,这个 xpath 表达式会让我得到所有 id 节点的集合,对吗?但我想要的是项目节点的集合:
Say, this xpath expression would get me the collection of all the id nodes, right? But what I want is the collection of item nodes:
XPathExpression expr = xpath.compile("/root/item/id[@isInStock='true']");
我知道我应该使用父级"轴来指代那个,但我就是做对了...
I know I should use the "parent" axis to refer to that, but I just cannot make it right...
有没有更好的方法来做这种事情?现在学习 w3cschools 教程...
Is there a better way of doing this sort of thing? Learning the w3cschools tutorials now...
抱歉,我是 Java 中的 XPath 新手,在此先感谢您.
Sorry I am new to XPath in Java, and thanks a lot in advance.
推荐答案
如果我想得到一个过滤"的子集这个 XML 中的 item 元素,如何我可以使用 XPath 表达式吗直接解决那个?
If I wanna get a "filtered" subset of the item elements from this XML, how could I use an XPath expression to directly address that?
一个示例 XPath 表达式:
An example XPath expression:
/*/item[id/@isInStock='true']/category/text()
此 XPath 表达式选择 isInStock
属性的所有
元素的所有
元素的所有文本节点子节点其中 id
子元素的值为 'true'
并且(id
元素)是 XML 文档顶部元素的子元素.
This XPath expression selects all text-node children of all <category>
elements of all <item>
elements the isInStock
attribute of whose id
child has a value of 'true'
and (the id
elements) that are children of the top element of the XML document.
另一个问题是:我怎么能正确引用父节点?
Another question is : how could I refer to the parent node properly?
使用:
parent::node()
或者干脆
..
这篇关于如何使用 XPath 按 TextContent 过滤元素?通过轴获取父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!