这种转变:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pNum" select="3"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Class[History]">
<xsl:choose>
<xsl:when test="not(position() = $pNum)">
<xsl:call-template name="identity"/>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<AddThis>Ok</AddThis>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
应用于提供的 XML 文档时:
<College>
<Class>
<History>
<StudentName>Veronica</StudentName>
</History>
</Class>
<Class>
<History>
<StudentName>Jasmine</StudentName>
</History>
</Class>
<Class>
<History>
<StudentName>Rebecca</StudentName>
</History>
</Class>
</College>
产生想要的正确结果:
<College>
<Class>
<History>
<StudentName>Veronica</StudentName>
</History>
</Class>
<Class>
<History>
<StudentName>Jasmine</StudentName>
</History>
</Class>
<Class>
<History>
<StudentName>Rebecca</StudentName>
</History>
<AddThis>Ok</AddThis>
</Class>
</College>
解释:非常典型的身份规则覆盖。
XSLT 2.0 解决方案:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pNum" select="3"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Class[History][position() = $pNum]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<AddThis>Ok</AddThis>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
说明:与 XSLT 1.0 解决方案几乎相同,但更短,因为在 XSLT 2.0 中,变量/参数引用在匹配模式中出现是合法的——因此我们完全摆脱了的显式条件。
更新:OP现在已经修改了问题:
"抱歉,"AddThis" 元素应该被添加到
第三个“历史”节点,不在第三个“历史”节点之外,我的错。一世
在我的问题帖子中更正了这一点。我将如何将您的 XSLT 1.0 编辑为
纠正这个?谢谢。 – 杀虫剂"
下面是相应修改的解决方案:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pNum" select="3"/>
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Class[History]">
<xsl:choose>
<xsl:when test="not(position() = $pNum)">
<xsl:call-template name="identity"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="." mode="add"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="node()|@*" mode="add" name="id2">
<xsl:copy>
<xsl:apply-templates select="node()|@*" mode="add"/>
</xsl:copy>
</xsl:template>
<xsl:template match="History/StudentName" mode="add">
<xsl:call-template name="id2"/>
<AddThis>Ok</AddThis>
</xsl:template>
</xsl:stylesheet>