带有后代和后代 text() 谓词的 XPath 查询
我想构造一个 XPath 查询,它将返回“div”或“table”元素,只要它有包含文本“abc”的后代。需要注意的是它不能有任何 div 或 table 后代。
<div>
<table>
<form>
<div>
<span>
<p>abcdefg</p>
</span>
</div>
<table>
<span>
<p>123456</p>
</span>
</table>
</form>
</table>
</div>
因此,此查询的唯一正确结果是:
/div/table/form/div
我的最佳尝试看起来像这样:
//div[contains(//text(), "abc") and not(descendant::div or descendant::table)] | //table[contains(//text(), "abc") and not(descendant::div or descendant::table)]
但没有返回正确的结果。
感谢您的帮助。
I would like to construct an XPath query that will return a "div" or "table" element, so long as it has a descendant containing the text "abc". The one caveat is that it can not have any div or table descendants.
<div>
<table>
<form>
<div>
<span>
<p>abcdefg</p>
</span>
</div>
<table>
<span>
<p>123456</p>
</span>
</table>
</form>
</table>
</div>
So the only correct result of this query would be:
/div/table/form/div
My best attempt looks something like this:
//div[contains(//text(), "abc") and not(descendant::div or descendant::table)] | //table[contains(//text(), "abc") and not(descendant::div or descendant::table)]
but does not return the correct result.
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有些不同::)
看起来比其他解决方案短很多,不是吗? :)
翻译为简单英语:对于文档中包含字符串
"abc"
的任何文本节点,选择其第一个祖先,即div
或表格
。这更高效,因为只需要对文档树(而不是任何其他)进行一次完整扫描,并且
ancestor::*
遍历与descendent::
(树)扫描。要验证此解决方案“确实有效”:
当对提供的 XML 文档执行此转换时:
生成所需的正确结果:
注意:没有必要使用 XSLT——任何 XPath 1.0 宿主——比如 DOM,都必须获得相同的结果。
Something different: :)
Seems a lot shorter than the other solutions, doesn't it? :)
Translated to simple English: For any text node in the document that contains the string
"abc"
select its first ancestor that is either adiv
or atable
.This is more efficient, as only one full scan of the document tree (and not any other) is required, and the
ancestor::*
traversal is very cheap compared to adescendent::
(tree) scan.To verify that this solution "really works":
when this transformation is performed on the provided XML document:
the wanted, correct result is produced:
Note: It isn't necessary to use XSLT -- any XPath 1.0 host -- such as DOM, must obtain the same result.
contains(//text(), "abc")
的问题是函数强制转换采用第一个节点的节点集。The problem with
contains(//text(), "abc")
is that functions cast node sets taking the first node.你可以试试:
这有帮助吗?
you could try:
does that help?