Xpath 不想 select 我的标签

Xpath doesn't want to select my tags

我有以下 HTML 代码,其中包含一个地址:

<html>
<body>
    <div>
        <h2>Address</h2>
        <p>
            Rotes Rathaus<br />
            Rathausstrasse<br />
            10178 Berlin<br />
            Germany<br />
        </p>
    </div>
</body>
</html>

我试图找到包裹地址的段落节点(在我的例子中:<p> 标签),我所拥有的只是地址部分的数组(例如:'Rathaus', 'Berlin', '10178').

我正在使用以下 XPath 选择器查询 dom:

//*[contains(text(),'Rathaus')]

效果很好,returns 遇到了

节点。但是,当我根据 postalCode 查找时,我没有找到任何匹配项:

//*[contains(text(),'10178')]

我需要做什么才能解决这个问题? 请注意,地址的位置可以在页面的任意位置。

此致, 尼古拉斯

解决方案

使用

//*[text()[contains(.,'10178')]]

并且 p 元素将作为结果被选中。意思是

look for any element node anywhere in the document, but only if there is at least one child text node whose string value contains "10178".

另一方面,你原来的表达:

//*[contains(text(),'10178')]

表示:

look for any element node anywhere in the document, but only if the first of its child text nodes contains the string "10178".

说明

由于函数在 XPath 1.0 中的工作方式,您对结果感到惊讶。像 contains() 这样的函数需要一个节点作为第一个参数。如果交给它一组节点,它只会处理第一个而忽略其余的。

您需要了解的另一件事是,由子元素分隔的文本最终会出现在单独的文本节点中。因此,P 的文本内容实际上被分割成几个文本节点,因为中间有 br 元素。

您可以通过评估像

这样的表达式来检查这一点
//p/node()           |  Find `p` elements anywhere in the document and return all nodes
                        that are their children, regardless of the type of node.

在您展示的文档上,它将return(个别结果以-------分隔):

            Rotes Rathaus
-----------------------
<br/>
-----------------------

            Rathausstrasse
-----------------------
<br/>
-----------------------

            10178 Berlin
-----------------------
<br/>
-----------------------

            Germany
-----------------------
<br/>
-----------------------

如您所见,只要中间有 brp 的文本内容就会存储在单独的文本节点中。此时您应该意识到,如果“10178”恰好在 first 文本节点而不是第三个文本节点中,您的原始表达式就会起作用。也许你能猜到 //p/text()[3] 会产生什么?


最后提示:这在 XPath 2.0 中发生了变化,其中不止一项是真正的节点序列,函数将依次处理每个节点。