Reputation: 1020
I have xml like follows,
<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>
what I need is add new node named <newNode>
conditionally. the xsl I've written is follows,
<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>
My requirement is if var
value is true()
add new node under section 3 and if var
value is false()
add new node under final section node. I've written to add <newNode>
under both section 3 and final section. but cannot think of method to conditionally check var value and add <newNode>
accordingly.
How can I do this task in xslt?
Upvotes: 1
Views: 213
Reputation: 163272
Simplified version of @MartinHonnen 's answer
<xsl:template match="section[position()=(if ($var) then 3 else last())]">
<section id="{@id}">
<xsl:apply-templates/>
</section>
<newNode>New Node</newNode>
</xsl:template>
Upvotes: 4
Reputation: 1239
Variation in style of Martin Honnen's answer: in case there was reason to limit match
to node selection, you could also place whatever depends on $var
in a conditional inside the templates,
<xsl:template match="...">
<xsl:if test="not($var)">
<section id="{@id}">
...
Upvotes: -1
Reputation: 167471
Simply use
<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>
Upvotes: 2