XPath 在任何文本节点中查找文本 [英] XPath find text in any text node

查看:26
本文介绍了XPath 在任何文本节点中查找文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在文档的任何文本节点中查找某个文本,到目前为止我的语句如下所示:

I am trying to find a certain text in any text node in a document, so far my statement looks like this:

doc.xpath("//text() = 'Alliance Consulting'") do |node|
  ...
end

这显然行不通,谁能提出更好的替代方案?

This obviously does not work, can anyone suggest a better alternative?

推荐答案

此表达式 //text() = 'Alliance Consulting' evals 为布尔值.

This expression //text() = 'Alliance Consulting' evals to a boolean.

如果是这个测试样本:

<r>
    <t>Alliance Consulting</t>
    <s>
        <p>Test string
            <f>Alliance Consulting</f>
        </p>
    </s>
    <z>
        Alliance Consulting
        <y>
            Other string
        </y>
    </z>
</r>

它当然会返回true.

你需要的表达式应该计算为节点集,所以使用:

Expression you need should evaluate to node-set, so use:

//text()[. = 'Alliance Consulting']

例如表达:

count(//text()[normalize-space() = 'Alliance Consulting'])

针对上述文件将返回3.

要选择在整个字符串值中包含 'Alliance Consulting' 的文本节点(例如 'Alliance Consulting provides great services'),请使用:

To select text nodes which contain 'Alliance Consulting' in the whole string value (e.g. 'Alliance Consulting provides great services') use:

//text()[contains(.,'Alliance Consulting')]

请注意相邻文本节点在解析器到达文档后应该成为一个.

Do note that adjacent text nodes should become one after parser gets to the document.

这篇关于XPath 在任何文本节点中查找文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆