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. The following XPath selects all div
tags in a document:
我正在编写一个JavaScript函数,可以用HTML代码替换文本,但要做到这一点,我需要能够以文本节点的形式访问文本。以下XPath选择文档中的所有div标记:
//div
The following XPath selects all elements with the attribute class
assigned the value myclass
:
以下XPath选择具有赋值myclass的属性类的所有元素:
//*[@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注释的元素下面的任何级别的所有文本(不是文本节点):
//*[@id="comments"]//text()
What is an XPath that can be used to select all text nodes under any element? 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. Would it use text()
in the query?
什么是XPath可用于选择任何元素下的所有文本节点?所以,假设我想要替换字符串Hebert的所有非注释事件,并且我需要所有文本节点,以便我可以扫描它们以查找该字符串。它会在查询中使用text()吗?
1 个解决方案
#1
5
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":
要选择字符串值为“Herbert”的所有文本节点:
//text()[.='Herbert']
Note that your comment,
请注意你的评论,
The following selects all of the text (not text nodes)
以下选择所有文本(不是文本节点)
regarding the XPath, //text()
, is incorrect. The node test text()
selects text nodes. In a string context, it will return the string-value of the text node, but text()
alone most certainly selects actual text nodes.
关于XPath,// text(),是不正确的。节点测试文本()选择文本节点。在字符串上下文中,它将返回文本节点的字符串值,但text()单独肯定会选择实际的文本节点。
See also Testing text() nodes vs string values in XPath
另请参阅在XPath中测试text()节点与字符串值
#1
5
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":
要选择字符串值为“Herbert”的所有文本节点:
//text()[.='Herbert']
Note that your comment,
请注意你的评论,
The following selects all of the text (not text nodes)
以下选择所有文本(不是文本节点)
regarding the XPath, //text()
, is incorrect. The node test text()
selects text nodes. In a string context, it will return the string-value of the text node, but text()
alone most certainly selects actual text nodes.
关于XPath,// text(),是不正确的。节点测试文本()选择文本节点。在字符串上下文中,它将返回文本节点的字符串值,但text()单独肯定会选择实际的文本节点。
See also Testing text() nodes vs string values in XPath
另请参阅在XPath中测试text()节点与字符串值