Xml XSLT-有条件地添加新节点
我有如下xmlXml XSLT-有条件地添加新节点,xml,xslt,xslt-2.0,Xml,Xslt,Xslt 2.0,我有如下xml <doc> <section id="1">This is <style type="normal">first</style> chapter</section> <section id="2">This is <style type="normal">second</style> chapter</section> <section id=
<doc>
<section id="1">This is <style type="normal">first</style> chapter</section>
<section id="2">This is <style type="normal">second</style> chapter</section>
<section id="3">This is <style type="normal">third</style> chapter</section>
<section id="4">This is <style type="normal">forth</style> chapter</section>
<section id="5">This is <style type="normal">fifth</style> chapter</section>
<section id="6">This is <style type="normal">sixth</style> chapter</section>
<section id="7">This is <style type="normal">seventh</style> chapter</section>
</doc>
我需要的是有条件地添加名为的新节点。我编写的xsl如下所示
<xsl:variable name="var" as="xs:boolean" select="true()"/>
<xsl:template match="section[position()=last()]">
<section id="{@id}">
<xsl:apply-templates/>
</section>
<newNode>New Node</newNode>
</xsl:template>
<xsl:template match="section[position()=3]">
<section id="{@id}">
<xsl:apply-templates/>
</section>
<newNode>New Node</newNode>
</xsl:template>
我的要求是,如果var值为true,则在第3节下添加新节点,如果var值为false,则在最后一节节点下添加新节点。我在第3节和最后一节中都写了补充内容。但不能想到有条件地检查var值并相应地添加的方法
如何在xslt中完成此任务?只需使用
<xsl:template match="section[not($var) and position()=last()]">
<section id="{@id}">
<xsl:apply-templates/>
</section>
<newNode>New Node</newNode>
</xsl:template>
<xsl:template match="section[$var and position()=3]">
<section id="{@id}">
<xsl:apply-templates/>
</section>
<newNode>New Node</newNode>
</xsl:template>
简单使用
<xsl:template match="section[not($var) and position()=last()]">
<section id="{@id}">
<xsl:apply-templates/>
</section>
<newNode>New Node</newNode>
</xsl:template>
<xsl:template match="section[$var and position()=3]">
<section id="{@id}">
<xsl:apply-templates/>
</section>
<newNode>New Node</newNode>
</xsl:template>
Martin Honnen回答风格的变化:如果有理由限制匹配到节点选择,也可以将依赖于$var的任何内容放在模板内的条件中
<xsl:template match="...">
<xsl:if test="not($var)">
<section id="{@id}">
...
Martin Honnen回答风格的变化:如果有理由限制匹配到节点选择,也可以将依赖于$var的任何内容放在模板内的条件中
<xsl:template match="...">
<xsl:if test="not($var)">
<section id="{@id}">
...
@MartinHonnen答案的简化版本
<xsl:template match="section[position()=(if ($var) then 3 else last())]">
<section id="{@id}">
<xsl:apply-templates/>
</section>
<newNode>New Node</newNode>
</xsl:template>
@MartinHonnen答案的简化版本
<xsl:template match="section[position()=(if ($var) then 3 else last())]">
<section id="{@id}">
<xsl:apply-templates/>
</section>
<newNode>New Node</newNode>
</xsl:template>