Chanan Ippel
Chanan Ippel

Reputation: 28

How to replace an XML attribute using XSLT when a certain other attribute is filled?

I got two possible XML files:

<orders>
   <order id="1">
      <code value="001-AAA"/>
      <altCode value="002-BBB"/>
   </order>
</orders>

And:

<orders>
   <order id="2">
      <code value="001-AAA"/>
      <altCode value=""/>
   </order>
</orders>

I would like the <code>tag's value attribute to be replaced by the <altCode>tag's value attribute, unless the second value is empty. In that case I would like the XML te remain unchanged. The <altCode>tag doesn't need to be changed.

So the resulting two XML files should look like this:

<orders>
   <order id="1">
      <code value="002-BBB"/>
      <altCode value="002-BBB"/>
   </order>
</orders>

And:

<orders>
   <order id="2">
      <code value="001-AAA"/>
      <altCode value=""/>
   </order>
</orders>

Note: The actual files I like to convert are a lot more complex. So I prefer to copy the template and change the attribute after with a when-statement.

Any help is very much appreciated.

Upvotes: 0

Views: 100

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

I would suggest you do:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="code/@value[string(../../altCode/@value)]">
    <xsl:copy-of select="../../altCode/@value"/>
</xsl:template>

</xsl:stylesheet>

Upvotes: 2

Related Questions