sh1nen
sh1nen

Reputation: 199

XSLT transformation retrieving children of element with its subchildren

I am trying to transform simple xml with xslt, but I got stuck on really easy case, though I couldn't find any examples how to solve it correctly. Here is my xml structure:

<TrackList>
   <Track no="1">
      <Title>Tin Man</Title>
   </Track >
   <Track no="2">
      <Title>Good Ol Days</Title>
    </Track >
    <Track no="3">
      <Title>Thing That Break</Title>
    </Track >
</TrackList>

I would like to retrieve all tracks from TrackList so I could have:

<TrackList>
   <Track title=""/>
   <Track title=""/>
   <Track title=""/>
</TrackList>

I tried following xslt templates:

<xsl:element name="TrackList">
   <xsl:apply-templates select="TrackList"/>
 </xsl:element>

 <xsl:template match="//TrackList">
    <xsl:element name="Track">
       <xsl:attribute name="title">
          <xsl:value-of select="Track/Title"/>
        </xsl:attribute>
    </xsl:element>
</xsl:template>

Though I am only getting the first element extracted properly but the rest is ignored, could someone explain and advice how it could be done properly retrieved.

Upvotes: 0

Views: 98

Answers (2)

imran
imran

Reputation: 461

 <xsl:template match="TrackList">
       <xsl:element name="TrackList">
           <xsl:for-each select="Track">
               <xsl:element name="Track">
                   <xsl:attribute name="title">
                       <xsl:value-of select="Title"/>
                   </xsl:attribute>
               </xsl:element>
           </xsl:for-each>
           </xsl:element>
   </xsl:template>

Upvotes: 0

Martin Honnen
Martin Honnen

Reputation: 167716

If you want to transform the Track elements then write a template

  <xsl:template match="Track">
      <Track title="{Title}"/>
  </xsl:template>

for them, handle the rest by the identity transformation template:

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Track">
      <Track title="{Title}"/>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/94hvTz3

Upvotes: 1

Related Questions