Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the value of an attribute depending of the value of a second attribute of the same element

This is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <trans>
       <language type="lang" lang="DE"/>
    </trans>
    <trans>
       <language type="lang" lang="EN"/>
    </trans>
</root>

My goal is to replace the value of the attribute "type" depending on the value specified in the "lang" attribute.

This is the desired output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <trans>
       <language type="German" lang="DE"/>
    </trans>
    <trans>
       <language type="English" lang="EN"/>
    </trans>
</root>

I have started with the following but don't get any further at this point:

   <xsl:template match="language">
    <xsl:choose>
     <xsl:when test="@lang=DE">
       <xsl:attribute name="type">
         <xsl:value-of select="'German'"/>
   <xsl:apply-templates/>
     </xsl:when>
    <xsl:otherwise>
    ???

Any help appreciated.

like image 901
bimmer Avatar asked Jan 30 '26 16:01

bimmer


1 Answers

Try these 3 templates (1st one is an identity template; second will "eat up" all @type; and third one will generate both attributes again, based on the @type):

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

<xsl:template match="//language/@type"/>

<xsl:template match="//language/@lang">
  <xsl:attribute name="lang">
    <xsl:value-of select="."/>
  </xsl:attribute>
  <xsl:attribute name="type">
    <xsl:choose>
      <xsl:when test=".='DE'">German</xsl:when>
      <xsl:when test=".='EN'">English</xsl:when>
      <xsl:otherwise>Other</xsl:otherwise>
    </xsl:choose>
  </xsl:attribute>
</xsl:template>
like image 111
rohit_wason Avatar answered Feb 01 '26 09:02

rohit_wason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!