Search code examples
xsltxslt-2.0xslcompiledtransform

xslt Parsing in .NET


Consider following snippet code for xml.

<rootnode>
    <child id="child1" ><![CDATA[child 1]]></child>
    <child id="child2" ><![CDATA[child 2]]></child>
    <child id="child3" ><![CDATA[child 3]]></child>
    <child id="child4" ><![CDATA[child 4]]></child>
    <child id="child5" ><![CDATA[child 5]]></child>
    <child id="child6" ><![CDATA[child 6]]></child>
    <child id="A1" ><![CDATA[A 1]]></child>
    <child id="A2" ><![CDATA[A 2]]></child>
    <child id="A3" ><![CDATA[A 3]]></child>
    <child id="A4" ><![CDATA[A 4]]></child>
    <child id="A5" ><![CDATA[A 5]]></child>
    <child id="A6" ><![CDATA[A 6]]></child>
</rootnode>

I want to iterate through all the child having id like 'child' using xslt.
How do I achieve this?


Solution

  • Its worth learning to not just reach for a for each loop in XSLT - this is a template matching approach to the same thing:

    <xsl:template match="/rootnode">
        <xsl:apply-template select="child[starts-with(@id, 'child')]" />
    </xsl:template>
    
    <xsl:template match="child">
        <!-- Do stuff -->
    </xsl:template>
    

    The key bit is the xpath query in square brackets - something that ajay_whiz also suggested for the for-each loop.