如何用XSLT 1.0复制所有节点并仅保留指定重复节点的最后一个实例?
XSLT 1.0 保留最后一个
<repeat>节点的解决方案 以下是实现需求的XSLT 1.0代码:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 身份模板:默认复制所有未被特殊匹配的节点 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 匹配并忽略所有非最后一个的<repeat>节点 --> <xsl:template match="repeat[not(position() = last())]"/> </xsl:stylesheet>
代码说明
- 身份模板:这是XSLT的基础模板,会原样复制所有未被其他模板匹配的节点(包括
<parent>、<header>、<repeating>容器,以及最后一个<repeat>的子元素)。 - 过滤模板:核心逻辑是匹配所有
position()不等于last()的<repeat>节点,这类节点会被直接忽略(模板内容为空,不输出)。这里的position()和last()的计算上下文是<repeating>的子节点集合,确保只保留最后一个<repeat>。
如果之前的尝试失败,通常是因为last()的上下文错误——比如未限定<repeat>的父节点为<repeating>,导致last()计算的是其他节点集合的长度,而非目标列表的长度。
另一种实现方式
你也可以直接匹配<repeating>节点,只处理其最后一个<repeat>子节点,效果相同:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="repeating"> <xsl:copy> <xsl:apply-templates select="repeat[last()]"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
将上述任意一份XSLT应用到你的输入XML,即可得到期望的输出结果。
内容的提问来源于stack exchange,提问作者aztekxero
相关产品推荐
相关产品推荐

