XSLT,找出最后一个子节点是否是特定元素 [英] XSLT, finding out if last child node is a specific element
问题描述
看下面两个例子:
<foo>some text <bar/> and maybe some more</foo>
和
<foo>some text <bar/> and a last <bar/></foo>
混合文本节点和 foo
元素内的 bar
元素.现在我在 foo
中,想知道最后一个孩子是否是 bar
.第一个例子应该证明是错误的,因为 bar
后面有文本,但第二个例子应该是真的.
Mixed text nodes and bar
elements within the foo
element. Now I am in foo
, and want to find out if the last child is a bar
. The first example should prove false, as there are text after the bar
, but the second example should be true.
如何使用 XSLT 完成此操作?
How can I accomplish this with XSLT?
推荐答案
只需选择
元素的最后一个节点,然后使用self
轴解决节点类型.
Just select the last node of the <foo>
element and then use self
axis to resolve the node type.
/foo/node()[position()=last()]/self::bar
如果最后一个节点不是元素,则此 XPath 表达式返回一个空集(相当于布尔值 false).如果要专门获取值true
或false
,请将此表达式包装在XPath 函数boolean()
中.使用 self::*
而不是 self::bar
来匹配任何元素作为最后一个节点.
This XPath expression returns an empty set (which equates to boolean false) if the last node is not an element. If you want to specifically get value true
or false
, wrap this expression in the XPath function boolean()
. Use self::*
instead of self::bar
to match any element as the last node.
输入 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
这篇关于XSLT,找出最后一个子节点是否是特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!