[xsl] Insert new element depending on value of attribute

Subject: [xsl] Insert new element depending on value of attribute
From: Gerhard Glatz <Gerhard21@xxxxxxx>
Date: Mon, 18 Feb 2008 19:10:51 +0100
Hello Everyone,

I have something like this, where there can be any number of <track> elements and sometimes there is a <multipart> element.
Most of the elements do have attributes.


<root>
   <disk>
      <tracks>
         <track>
            <multipart></mulitpart>
            <length></length>
            <measure></measure>
         </track>
         <track>
            <length></length>
            <measure></measure>
         </track>
      </tracks>
   <disk>
   <disk>
      <tracks>
         <track>
            <length></length>
            <measure></measure>
         </track>
         <track>
            <length></length>
            <measure></measure>
         </track>
      </tracks>
      <tracks>
         <track>
            <length></length>
            <measure></measure>
         </track>
         <track>
            <multipart></mulitpart>
            <length></length>
            <measure></measure>
         </track>
      </tracks>
   <disk>
</root>

Depending on the value of the <multipart> element I want to insert another <track> element in that specific <tracks>, but it has to be the last one.
The lines below work fine for inserting a new <track> element in every <disk>. And I tried a lot to figure out a way for


What the lines below do:
- Copy all nodes
- Insert a new element <track> in every <disk> at the last position

What I want them to do:
- Copy all nodes
- Insert a new element <track> in every <disk> at the last position only if an attribute of <multipart> has a specific value.


<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>


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

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

      <xsl:if test="position()=last()">
         <xsl:element name="track">
            <xsl:attribute name="length">....</xsl:attribute>
            ...
         </xsl:element>

      </xsl:if>
   </xsl:template>

</xsl:stylesheet>

I tried a lot of different positions of another <xsl:if>, but all I got, was either the result above, or a mulitple insertion of new <track> elements.

Does anybody have a hint, where and how I should add something like
<xsl:if test="multipart/@attribute=desired_value"> ??

I'm using xslt 1.0 and xmlstarlet (http://xslstar.sourceforge.net)

Thank you very much.

Gerhard

Current Thread