Creating New Attributes

To create a new attribute in the output document, you need to use the xsl:attribute element.

On this occasion, you will transform a source document in the U.K. company’s format to an XML output document in the U.S. company’s format. Listing 11.9 shows an XSLT stylesheet that can carry out the transformation.

Listing 11.9. UKShirtsToUS.xsl: An XSLT Stylesheet to Transform to the U.S. Company’s Data Format
<?xml version='1.0'?> 
<xsl:stylesheet 
 version="1.0" 
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
 > 
<xsl:output method="xml" indent="yes" encoding="UTF-8" /> 
<xsl:template match="/"> 
<USShirts> 
<Order> 
<xsl:apply-templates select="/UKShirts" /> 
</Order> 
</USShirts> 
</xsl:template> 

<xsl:template match="Order" > 
<xsl:apply-templates select="Date" /> 
<xsl:apply-templates select="From" /> 

<xsl:apply-templates select="To" /> 
<xsl:apply-templates select="Shirt" /> 
</xsl:template> 

<xsl:template match="Date" > 
<xsl:copy-of select="." /> 
</xsl:template> 

<xsl:template match="From|To" > 
<xsl:copy-of select="." /> 
</xsl:template> 

<xsl:template match="Shirt"> 
<xsl:copy>  
<xsl:attribute name="size"> 
<xsl:value-of select="Size" /> 
</xsl:attribute> 
<xsl:apply-templates select="Colour" /> 
<xsl:apply-templates select="Quantity" /> 
</xsl:copy> 
</xsl:template> 

<xsl:template match="Colour"> 
<xsl:element name="Color"> 
<xsl:value-of select="." /> 
</xsl:element> 
</xsl:template> 

<xsl:template match="Quantity"> 
<xsl:copy-of select="." /> 
</xsl:template> 

</xsl:stylesheet> 

Use the xsl:attribute in the template that matches the Shirt element node:

<xsl:template match="Shirt"> 
<xsl:copy> 
<xsl:attribute name="size"> 
<xsl:value-of select="Size" /> 
</xsl:attribute> 
<xsl:apply-templates select="Colour" /> 
<xsl:apply-templates select="Quantity" /> 
</xsl:copy> 
</xsl:template> 

First copy the Shirt element using xsl:copy. Then use the xsl:attribute element to add an attribute to the Shirt element. The value of that new shirt attribute is obtained from the content of the Size element. The first xsl-apply-templates element is used to create a new Color element to replace the Colour element used by the U.K. company’s format.

If you can carry out shallow and deep copies and create new elements and new attributes, you can accomplish many of the basic tasks that are necessary in converting one XML format to another.

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

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