Converting Attributes into Elements

 
xslt for dummies
Chapter 6 - We Want Results!
XSLT For Dummies
by Richard Wagner
Hungry Minds 2002
  

You can also perform the opposite action and convert attributes into elements. As a demonstration of this technique as well as others Ive shown in this chapter, I am going to create a new XML structure based on coffee.xml , but with several changes:

  • Convert the region elements name attribute into a name child element.

  • Add a new source element under coffee that gets its value based on the region elements name and the coffee elements origin attribute.

  • Move the content of the price element to be the value of a new retail attribute and add a new wholesale attribute to price that is 60 percent of the retail value.

The following stylesheet sets up these conversions:

 <!-- coffee-convert_to_elem.xsl.xsl --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <!-- Move region name to be a child element of region --> <xsl:template match="region"> <region> <name><xsl:value-of select="@name"/></name> <xsl:apply-templates/> </region> </xsl:template> <!-- Convert coffee element --> <xsl:template match="coffee"> <coffee> <price retail="{price}" wholesale="{format-number(price*.6, '##.##')}"></price> <source><xsl:value-of select="../@name"/><xsl:value-of select="@origin"/></source> <availability><xsl:value-of select="availability"/></availability> <xsl:apply-templates/> </coffee> </xsl:template> <!-- Remove elements --> <xsl:template match="taste"/> <xsl:template match="price"/> <xsl:template match="availability"/> <xsl:template match="bestwith"/> </xsl:stylesheet> 

When this stylesheet is run against the coffee.xml file, the results from the transformation are as follows :

 <?xml version="1.0" encoding="utf-8"?> <region> <name>Latin America</name> <coffee> <price retail="11.99" wholesale="7.19"/> <source>Latin AmericaGuatemala</source> <availability>Year-round</availability> </coffee> <coffee> <price retail="12.99" wholesale="7.79"/> <source>Latin AmericaCosta Rica</source> <availability>Year-round</availability> </coffee> </region> <region> <name>Africa</name> <coffee> <price retail="14.99" wholesale="8.99"/> <source>AfricaEthiopia</source> <availability>Limited</availability> </coffee> <coffee> <price retail="9.99" wholesale="5.99"/> <source>AfricaKenya</source> <availability>Year-round</availability> </coffee> </region> 
  
 
 
2000-2002    Feedback


XSLT For Dummies
XSLT for Dummies
ISBN: 0764536516
EAN: 2147483647
Year: 2002
Pages: 148

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net