看下面两个例子:
<foo>some text <bar/> and maybe some more</foo>
and
<foo>some text <bar/> and a last <bar/></foo>
混合文本节点和bar
内的元素foo
元素。现在我在foo
,并想知道最后一个孩子是否是bar
。第一个例子应该被证明是错误的,因为后面有文本bar
,但第二个例子应该是正确的。
我如何使用 XSLT 来完成此任务?
只需选择最后一个节点<foo>
元素,然后使用self
axis 来解析节点类型。
/foo/node()[position()=last()]/self::bar
如果最后一个节点不是元素,则此 XPath 表达式返回一个空集(相当于布尔值 false)。如果你想专门获得价值true
or false
,将此表达式包装在 XPath 函数中boolean()
. Use self::*
代替self::bar
匹配任何元素作为最后一个节点。
输入XML文档:
<root>
<foo>some text <bar/> and maybe some more</foo>
<foo>some text <bar/> and a last <bar/></foo>
</root>
XSLT 文档示例:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="foo">
<xsl:choose>
<xsl:when test="node()[position()=last()]/self::bar">
<xsl:text>bar element at the end </xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>text at the end </xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
样式表的输出:
text at the end
bar element at the end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)