我希望将两个或多个祖先标记中的相同属性组合到我在模板中匹配的标记中。
示例输入:
<tag1 indent="up2">
<tag2 indent="up1">
<tag3></tag3>
</tag2>
</tag1>
示例输出:
<tag1 indent="up2">
<tag2 indent="up1">
<tag3 indent="up3"></tag3>
</tag2>
</tag1>
基本上,我正在寻找子标签来继承祖先的缩进 - 也可能有其他级别(级别的数量可能会改变)。也可能有“向下”标签。
我想做的是将“up”替换为“+”然后“down”替换为“ - ”,进行数学运算然后将其放入。
答案 0 :(得分:1)
如下:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*[@indent]">
<xsl:param name="prev-indent" select="0"/>
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="node()">
<xsl:with-param name="prev-indent" select="translate($prev-indent, 'dupown', '-') + translate(@indent, 'dupown', '-')" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:param name="prev-indent" select="0"/>
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="indent">
<xsl:choose>
<xsl:when test="$prev-indent < 0">
<xsl:text>down</xsl:text>
<xsl:value-of select="-$prev-indent" />
</xsl:when>
<xsl:otherwise>
<xsl:text>up</xsl:text>
<xsl:value-of select="$prev-indent" />
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
由于您使用的是XSLT 2.0,因此可以将其简化为:
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[not(@indent)]">
<xsl:variable name="indent" select="sum(ancestor::*/number(translate(@indent, 'dupown', '-')))" />
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="indent" select="concat(if ($indent lt 0) then 'down' else 'up', abs($indent))"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>