Moving an Attribute

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

An attribute describes something about the element in which it is contained and is treated as a child attribute node by the XSLT processor. On occasion, you may find it necessary to move an attribute from one element to another. To demonstrate , suppose I want to get rid of the region element in the coffee.xml document and replace it with a new region attribute in the coffees element. To do this, the value of the region elements name attribute needs to become the value of the region attribute by using the following stylesheet:

 <!-- coffee-move_attr.xsl --> <xsl:stylesheet xmlns:xsl="" version="1.0"> <!-- Move region name to be an attribute of coffees --> <xsl:template match="coffees"> <coffees region="{region/@name}"> <xsl:apply-templates/> </coffees> </xsl:template> <!-- Copy coffee elements as is --> <xsl:template match="coffee"> <xsl:copy-of select="."/> </xsl:template> </xsl:stylesheet> 

The coffees template rule recreates the coffees element, and uses the attribute value template {region/@name} to provide the value for the new region attribute. The coffee elements are simply copied over using the second template rule. These instructions produce output as shown here:

 <?xml version="1.0" encoding="utf-8"?> <coffees region="Latin America"> <coffee name="Guatemalan Express" origin="Guatemala"> <taste>Curiously Mild And Bland</taste> <price>11.99</price> <availability>Year-round</availability> <bestwith>Breakfast</bestwith> </coffee> <coffee name="Costa Rican Deacon" origin="Costa Rica"> <taste>Solid Yet Understated</taste> <price>12.99</price> <availability>Year-round</availability> <bestwith>Dessert</bestwith> </coffee> <coffee name="Ethiopian Sunset Supremo" origin="Ethiopia"> <taste>Exotic and Untamed</taste> <price>14.99</price> <availability>Limited</availability> <bestwith>Chocolate</bestwith> </coffee> <coffee name="Kenyan Elephantismo" origin="Kenya"> <taste>Thick And Chewy</taste> <price>9.99</price> <availability>Year-round</availability> <bestwith>Elephant Ears</bestwith> </coffee> </coffees> 
2000-2002    Feedback

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

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: