Basic XML/XSLT - value-of when there are multiple elements of the same name

lionysis picture lionysis · Dec 4, 2011 · Viewed 32.3k times · Source

When I'm getting the value of an element which is used multiple times in the same parent element, I'd like to get each element of the same name and not just the first.

E.g. -

<catalog>
<cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
            <artist>Bob Dylan2</artist>
            <artist>Bob Dylan3</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
</cd>
</catalog>

Now when I for-each through each CD and use value-of to output the artist name, I only get the first element (somewhat understandably). But how do I get ALL elements of the same name within a for-each loop? I tried doing an inner for-each loop but didn't work.

I'm very new to XML and how it works so please go easy on me...:-(

Answer

Siva Charan picture Siva Charan · Dec 4, 2011
<xsl:template match="/">
    <xsl:for-each select="catalog">
        <!-- Print Other Stuff, if required -->
        <xsl:for-each select="cd/artist">
            <xsl:value-of select="text()"/><br/>
        </xsl:for-each>
    </xsl:for-each>
</xsl:template>

Output:

Bob Dylan
Bob Dylan2
Bob Dylan3