Changing an Attribute to an Element

Due to the different ways in which people think about data, you are very likely to see the same item of data treated as an Attribute in one XML document and as an Element in someone else's idea of the same business document. In those types of situations you'll need to convert data between Elements and Attributes.

Here is a fairly common example. Most purchase orders list both a quantity and a unit of measure for a product item. Suppose that our order management system has the capability to import a purchase order in XML. Suppose that the designers decided to depict unit of measure and quantity as separate Elements in an overall line item Element. Suppose further that someone sends us a purchase order coded in compliance with some standard, wherein the standards developers considered that unit of measure was an attribute of quantity ordered rather than a stand-alone bit of data. We will need to convert this:

Source (AttributeToElement.xml)
<?xml version="1.0" encoding="UTF-8"?>
<LineItem>
  <QuantityOrdered UOM="CA">100</QuantityOrdered>
</LineItem>

into this:

Result (ElementToAttribute.xml)
<?xml version="1.0" encoding="UTF-8"?>
<LineItem>
  <UOM>CA</UOM>
  <QtyOrdered>100</QtyOrdered>
</LineItem>

The conversion is very easy, as shown below.

Stylesheet (AttributeToElement.xsl)
<?xml version="1.0" encoding="UTF-8"?>
<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:template match="/LineItem">
    <LineItem>
      <UOM>
        <xsl:value-of select="QuantityOrdered/@UOM"/>
      </UOM>
      <QtyOrdered>
        <xsl:value-of select="QuantityOrdered"/>
      </QtyOrdered>
    </LineItem>
  </xsl:template>
</xsl:stylesheet>

The at sign (@) preceding UOM in the location step tells the processor that we want the UOM Attribute of the QuantityOrdered Element.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset