xml 选择具有 XPath 的节点,其子节点包含特定的内部文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25221023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:04:47  来源:igfitidea点击:

Select a node with XPath whose child node contains a specific inner text

xmlxpath

提问by D.R.

Given the following XML:

给定以下 XML:

<root>
    <li><span>abcText1cba</span></li>
    <li><span>abcText2cba</span></li>
</root>

I want to select all lielements having a spanchild node containingan inner text of Text1- using an XPath.

我想选择所有li具有包含内部文本的span子节点的元素- 使用 XPath。Text1

I started off with /root/li[span]and then tried to further check with: /root/li[span[contains(text(), 'Text1')]]

我从开始/root/li[span],然后尝试进一步检查:/root/li[span[contains(text(), 'Text1')]]

However, this does not return any nodes. I fail to see why, can somebody help me out?

但是,这不会返回任何节点。我不明白为什么,有人可以帮我吗?

回答by Daniel Kereama

Just for readers. The xpath is correct. OP: Perhaps xpath parser didnt support the expression?

只为读者。xpath 是正确的。OP:也许 xpath 解析器不支持该表达式?

/root/li[span[contains(text(), "Text1")]]

回答by ViliamS

//li[./span[contains(text(),'Text1')]] - have just one target result
//li[./span[contains(text(),'Text')]] - returns two results as target

This approach is using something that isn't well documented anywhere and just few understands how it's powerful

这种方法使用的东西在任何地方都没有得到很好的记录,只有少数人了解它的强大之处

enter image description here

在此处输入图片说明

Element specified by Xpath has a child node defined by another xpath

Xpath 指定的元素有一个由另一个 xpath 定义的子节点

enter image description here

在此处输入图片说明

回答by Valiantsin Lopan

Try this XPath

试试这个 XPath

li/*[@innertext='text']

回答by Kent Kostelac

Your current xpath should be correct. Here is an alternative but ugly one.

您当前的 xpath 应该是正确的。这是另一种但丑陋的。

XmlNodeList nodes = doc.SelectNodes("//span/parent::li/span[contains(text(), 'Text1')]/parent::li");

We find all the span-tags. Then we find all the li-tags that has a span-tag as child and contains the 'Text1'.

我们找到了所有的跨度标签。然后我们找到所有具有 span-tag 作为子项并包含 'Text1' 的 li-tags。

OR simply:

或简单地:

//span[contains(text(), 'Text1')]/parent::li

//span[contains(text(), 'Text1')]/parent::li