我有一个XPath选择器,用于选择我想要的类://div[@class='myclass']
。但它会返回整个
(包括
<div class='myclass'>
),但我只想返回标签内的内容而不包括标签本身。有什么方法可以做到这一点吗?我有一个XPath选择器,用于选择我想要的类://div[@class='myclass']
。但它会返回整个
<div class='myclass'>
),但我只想返回标签内的内容而不包括标签本身。有什么方法可以做到这一点吗?node() = innerXml
text() = innerText
两者都是数组,所以text()[1]
是第一个子文本节点...
[]
之间的内容(你已经知道了),你的路径看起来像是pathElement[具有'value'为'my class'的'class'属性],其中pathElement直接在[
之前。[]
之外的所有内容都是路径,所以在//a/b/c[@blah='bleh']/d
中,a、b、c和d都是路径元素,blah是属性名,bleh是字面值。如果此路径匹配,则返回最后一个非条件元素d。x/text()
返回x的所有直接子文本,x/node()
返回所有子节点,包括文本。一则关于 IT 技术的常见问题的新回答:
针对这份 XML 文档,
<div class="myclass">content</div>
content
:
Text Node Selection
This XPath,
//div[@class='myclass']/text()
will select the text node children of the targeted div
element,
content
, as requested.
String Value of an Element
This XPath,
string(//div[@class='myclass'])
will return string-value of the targeted div
element,
content
, again as requested.
Further information: Here's a note explaining the string-values of elements:
The string-value of an element node is the concatenation of the string-values of all text node descendants of the element node in document order.
<div>text1<span>text2</span>text3</div>
就像我说的一样,它是一个数组,所以div/node()[0] == div/text()[0] == text1
节点,而div/node()[1] == span
节点,div/node()[2] == div/text()[1] == text3
节点 - 你需要自己将它们连接起来(手动或使用接受数组的辅助函数)。 - Nikola Bogdanović