Performing conditional checks when doing XSLT. Q. How to add element hasTagA to the result XML at the condition one or more tagA present in the source XML?

Roseanne Zhang

In XSLT, we has xsl:if xsl:choose xsl:when xsl:otherwise to perform conditional check. However, we can also use template with match attribute to perform conditional check. With the help of xpath predicate, it can do very powerful conditional check too. Here is an example.

XML sourece

<root>
    <tagA />
    <tagB />
    <tagC />
    <tagA />
</root>
XSLT sourece
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/root">
        <newroot>
            <xsl:apply-templates />
        </newroot>
    </xsl:template>
    <xsl:template match="*">
        <xsl:copy-of select="." />
    </xsl:template> 
    <!-- do something only on the first one -->
    <xsl:template match="tagA[1]" >
        <hasTagA>
            Do something here
        </hasTagA>
    </xsl:template>
    <!-- do nothing on the rest -->
    <xsl:template match="tagA[position() != 1]" /> 
</xsl:stylesheet>
XML result
<newroot>
    <hasTagA>
            Do something here
    </hasTagA>
    <tagB/>
    <tagC/>   
</newroot>
HTH! :)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact