[英]XPath for selecting all text nodes
I'm writing a JavaScript function that can be used to replace text with HTML code, but to do this I need to be able to access text in text node form. 我正在编写一个JavaScript函数,可以用HTML代码替换文本,但要做到这一点,我需要能够以文本节点的形式访问文本。 The following XPath selects all
div
tags in a document: 以下XPath选择文档中的所有
div
标记:
//div
The following XPath selects all elements with the attribute class
assigned the value myclass
: 以下XPath选择具有赋值
myclass
的属性class
所有元素:
//*[@class="myclass"]
The following selects all of the text (not text nodes) that occurs at any level underneath the element with the ID comments
: 以下选择具有ID
comments
的元素下面的任何级别的所有文本 (不是文本节点):
//*[@id="comments"]//text()
What is an XPath that can be used to select all text nodes under any element? 什么是XPath可用于选择任何元素下的所有文本节点? So, say I want to replace all the non-comment occurrences of the string
Hebert
and I need all of the text nodes so I can scan through them for that string. 所以,假设我想要替换字符串
Hebert
所有非注释事件,并且我需要所有文本节点,以便我可以扫描它们以查找该字符串。 Would it use text()
in the query? 它会在查询中使用
text()
吗?
Two options: 两种选择:
To select all text nodes whose string value contains the substring "Herbert": 要选择其字符串值包含子字符串“Herbert”的所有文本节点:
//text()[contains(.,'Herbert')]
To select all text nodes whose string value is "Herbert": 要选择所有文本节点,其字符串值是 “赫伯特”:
//text()[.='Herbert']
Note that your comment, 请注意你的评论,
The following selects all of the text (not text nodes)
以下选择所有文本(不是文本节点)
regarding the XPath, //text()
, is incorrect. 关于XPath,
//text()
,是不正确的。 The node test text()
selects text nodes. 节点测试
text()
选择文本节点。 In a string context, it will return the string-value of the text node, but text()
alone most certainly selects actual text nodes. 在字符串上下文中,它将返回文本节点的字符串值 ,但
text()
单独肯定会选择实际的文本节点。
See also Testing text() nodes vs string values in XPath 另请参阅在XPath中测试text()节点与字符串值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.