XPath返回符合条件的子节点值的字符串连接
-
05-07-2019 - |
题
任何人都可以建议一个XPath表达式格式,它返回一个字符串值,其中包含元素的某些符合条件的子节点的连接值,但忽略其他子节点:
<div>
This text node should be returned.
<em>And the value of this element.</em>
And this.
<p>But this paragraph element should be ignored.</p>
</div>
返回的值应该是单个字符串:
This text node should be returned. And the value of this element. And this.
这在单个XPath表达式中是否可行?
感谢。
解决方案
在XPath 1.0中:
您可以使用
/div//text()[not(parent::p)]
捕获有用的文本节点。连接本身不能在XPath 1.0中完成,我建议在宿主应用程序中完成。
其他提示
在XPath 2.0中:
string-join(/ * / node()[not(self :: p)],'')
/div//text()
无论中间节点如何,双斜杠强制提取文本
这看起来有效:
使用上下文 / div /
:
text() | em/text()
或者不使用上下文:
/div/text() | /div/em/text()
如果要连接前两个字符串,请使用:
concat(/div/text(), /div/em/text())
如果您想要除p以外的所有孩子,您可以尝试以下...
string-join(//*[name() != 'p']/text(), "")
返回......
This text node should be returned.
And the value of this element.
And this.
您也可以使用for-each循环并将值组合在一个像
这样的变量中<xsl:variable name="newstring">
<xsl:for-each select="/div//text()">
<xsl:value-of select="."/>
</xsl:for-each>
</xsl:variable>
不隶属于 StackOverflow