查詢具有特定文字的所有元素
想象一下以下 XML:
<root>
<element>hello</element>
<another>
hello
</another>
<example>Hello, <nested> I am an example </nested>.</example>
</root>
以下 XPath 表示式:
//*[text() = 'hello']
將返回 <element>hello</element> 元素,但不返回 <another> 元素。這是因為 <another> 元素包含 hello 文字週圍的空格。
要檢索 <element> 和 <another>,可以使用:
//*[normalize-space(text()) = 'hello']
要麼
//*[normalize-space() = 'hello']
這將在進行比較之前修剪周圍的空白。在這裡我們可以看到 text() 節點說明符在使用 normalize-space 時是可選的。
要查詢包含特定文字的元素,可以使用 contains 函式。以下表示式將返回 <example> 元素:
//example[contains(text(), 'Hello')]
如果要查詢跨越多個子節點/文字節點的文字,則可以使用 . 而不是 text()。. 指的是元素及其子元素的整個文字內容。
//example[. = 'Hello, I am an example .']
要檢視多個文字節點,你可以使用:
//example//text()
將返回:
- “你好, ”
- 我就是一個例子
- “”
為了更清楚地看到元素的整個文字內容,可以使用 string 函式:
string(//example[1])
要不就
string(//example)
你好,我是一個例子。
後者的工作原理是,如果將節點集傳遞給像 string 這樣的函式,XPath 1.0 只會檢視該節點集中的第一個節點(按文件順序),並忽略其餘節點。
所以:
string(/root/*)
會回來:
你好