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"开发者_如何学Go ><![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?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.
Your xslt will be
<xsl:template match="/rootnode">
<xsl:for-each select="child">
<xsl:if test="contains(@id,'child')">
... do your stuff here....
</xsl:if>
</xsl:for-each>
</xsl:template>
You can also use starts-with
function see http://www.w3schools.com/xpath/xpath_functions.asp
for complete reference
For efficiency you could define a key and use that e.g.
<xsl:key name="k1" match="child" use="starts-with(@id, 'child')"/>
<xsl:template match="rootnode">
<xsl:for-each select="key('k1', true())">
...
</xsl:for-each>
</xsl:template>
精彩评论