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

痞子三分冷 提交于 2021-01-21 03:55:01

问题


Given the following XML:

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

I want to select all li elements having a span child node containing an inner text of Text1 - using an XPath.

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

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


回答1:


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

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



回答2:


//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

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




回答3:


Try this XPath

li/*[@innertext='text']



回答4:


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

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'.

OR simply:

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



来源:https://stackoverflow.com/questions/25221023/select-a-node-with-xpath-whose-child-node-contains-a-specific-inner-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!