dscl
dscl

Reputation: 1626

XSLT - Looping through all child nodes

Don't shoot I'm just the messenger here, but I have some xml that looks like this

<XMLSnippet>
    <data>
        <stuff value="stuff" />
        <stuff value="more stuff" />
        <stuff value="even more stuff" />
        <widget value="you expected stuff didn't you" />
        <stuff value="great, we've got stuff again" />
    </data>
</XMLSnippet>

And I would like to loop through all the data child nodes and output the following

stuff
more stuff
even more stuff
you expected stuff didn't you
great, we've got stuff again

Should it matter I am limited to using XSLT 1.0

Thanks!

Upvotes: 8

Views: 64260

Answers (2)

dscl
dscl

Reputation: 1626

Thanks to Phil and the suggestions of Alexandre here is the code I got working

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:template match="/XMLSnippet">
       <xsl:for-each select="data/*">
          <xsl:value-of select="@value" />
       </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>

Upvotes: 22

PhillyNJ
PhillyNJ

Reputation: 3901

This is a basic XSLT question, so I am assuming you have little experience with xsl by your post. You need to understand how xslt processes a XML document which is beyond the scope of this post. Nevertheless, this should get you started. Please note, there are several ways to get the output you want, this is only one of them:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:template match="/">
    <xsl:apply-templates/>
</xsl:template>
<xsl:template match="XMLSnippet">
    <xsl:for-each select="data/stuff">
        <xsl:value-of select="@value"/>
    </xsl:for-each>
</xsl:template>

For starters, the template match="/" is your entry point. The apply-templates is an xslt instruction that tells the xslt processor to apply the template of the node in context. In this case your root node "XMLSnippet".

The for-each select="data/stuff" should be self explanatory as well as the value-of select="@value", except the @ is used to select an attribute.

Good Luck. May I suggest you read this book XSLT 2.0. A great book on XSLT.

Upvotes: 13

Related Questions