0

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.

1
  • "I prefer to copy the template and change the attribute after with a when-statement." What template? You haven't showed as any template, and we don't know what it matches, which is crucial. Commented Aug 22, 2017 at 10:58

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Michael! That's it. I got most of it, but got stuck on the last part. Could you explain that part? <xsl:template match="code/@value[string(../../altCode/@value)]"> <xsl:copy-of select="../../altCode/@value"/> </xsl:template> I know the @-part, but '[ ]', string and '../' are unknown to me. Just started XSLT a few day ago.
@ChananIppel The 2nd template matches the value attribute of code on the condition expressed in the [predicate] part. The predicate evaluates to true when the sibling's altCode/@value is not an empty string. Otherwise the attribute will be copied as is by the 1st template. ../ means go up to the parent level.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.