0

Given the following XML document:

<?xml version="1.0" encoding="utf-8"?>
<Store>
  <Location>
    <State>WA</State>
  </Location>
  <Transaction>
    <Category>Fruit</Category>
  </Transaction>
  <Customer>
    <Category>Rewards</Category>
  </Customer>
  <Document>
  <!-- Huge XML blob here -->
  </Document>
</Store>

How would I write an XSLT (version 1 or 2) to transform this to the following XML document:

<?xml version="1.0" encoding="utf-8"?>
<Transaction>
  <Account>
    <Type>Rewards</Type>
  </Account>
  <Type>
    <Department>Fruit</Department>
  </Type>
  <Document>
    <!-- Huge XML blob here -->
  </Document>
</Transaction>

?

Basically, I need to rearrange / rename some elements, drop some elements, and copy some elements just as they appear in the original.

  • The Store/Location/State element value is dropped.
  • The Store/Transaction/Fruit element is moved/renamed to Transaction/Type/Department.
  • The Store/Customer/Category is moved to Transaction/Account/Type.
  • The Store/Document element is copied along with all of its sub elements unchanged into the result as the Transaction/Document element.
Infin8Loop
  • 284
  • 3
  • 14

1 Answers1

1

You can use the following XSLT-1.0 stylesheet/template to achieve your goal:

<xsl:stylesheet version = "1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
 <xsl:output method="xml" indent="yes" />

<xsl:template match="Store">
    <Transaction>
        <Account>                            <!-- The Store/Customer/Category is moved to Transaction/Account/Type. -->
            <Type>
                <xsl:value-of select="Customer/Category" />
            </Type>
        </Account>
        <Type>                               <!-- The Store/Transaction/Fruit element is moved/renamed to Transaction/Type/Department. -->
            <Department>
                <xsl:value-of select="Transaction/Category" />
            </Department>
        </Type>
        <product>Rasberries</product>        <!-- Adding a new element with a constant value -->
        <xsl:copy-of select="Document" />    <!-- The Store/Document element is copied along with all of its sub elements unchanged into the result as the Transaction/Document element. -->
    </Transaction>
</xsl:template>

</xsl:stylesheet>

The Store/Location/State element value is dropped.

This is done by not mentioning it.

zx485
  • 28,498
  • 28
  • 50
  • 59
  • Thanks @zx485. What if I wanted to add a new element to the result, say a element whose value is hardcoded to "Rasberries". – Infin8Loop Jul 24 '18 at 18:20
  • You have been very helpful. Can you take a look at my new question? https://stackoverflow.com/questions/51519950/how-do-i-strip-add-namespaces-prefixes-in-this-xml-xslt – Infin8Loop Jul 25 '18 at 13:37