xml xpath 获取包含文本的节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6442430/
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 14:49:15  来源:igfitidea点击:

xpath to get Node containing text

xmlxpath

提问by Vjy

I tried to search for nodes containing text 'Yahoo' under '/doc/story/content', it returns 'content' node, but I need exact text node that contains 'Yahoo' or it's parent

我试图在“/doc/story/content”下搜索包含文本“雅虎”的节点,它返回“内容”节点,但我需要包含“雅虎”或其父节点的确切文本节点

<doc>
    <story>
        <content id="201009281450332423">
            <ul>MSW NYNES NYPG1 DILMA</ul>
            <p> <k> Yahoo, made </k> it nice </p>
            <p>
               <author>-v-</author>
            </p>
        </content>
    </story>
</doc>

Xpath: "/doc/story/content[contains(., 'Yahoo')]"

X路径: "/doc/story/content[contains(., 'Yahoo')]"

回答by Ravish

Since you need all textNodes only which contain the text Yahoo, use the following XPath.

由于您只需要包含文本Yahoo 的所有 textNodes ,请使用以下 XPath。

//text()[contains(., 'Yahoo')]

This should return you all the textNodes only which contains Yahoo(case-sensitive) in it.

这应该只返回包含Yahoo(区分大小写)的所有 textNodes 。

回答by Jon

Your XML is malformed. </content></doc></story>should be </content></story></doc>.

您的 XML 格式错误。</content></doc></story>应该是</content></story></doc>

Apart from that, the XPath you would want is

除此之外,您想要的 XPath 是

/doc/story/content//*[contains(., 'Yahoo')]

(select any descendant of <content>which contains the text "Yahoo" -- this will select the <p>)

(选择<content>包含文本“雅虎”的任何后代- 这将选择<p>