XSLT for Dummies
|
Chapter 6 - We Want Results! | |
XSLT For Dummies | |
by Richard Wagner | |
Hungry Minds 2002 |
Like adding elements to your result document, you can add attributes in one of two ways. You can create attributes both through literal text as well as the xsl:attribute instruction.
Using literal text
Using the literal text method, I can add a currency attribute to the price element of the coffee-light.xml document by using the following stylesheet:
<!-- coffee-addattribute_literal.xsl --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <!-- Add currency attribute --> <xsl:template match="coffee"> <coffee> <taste><xsl:value-of select="taste"/></taste> <price currency="$US"><xsl:value-of select="price"/></price> <availability><xsl:value-of select="availability"/></availability> <bestwith><xsl:value-of select="taste"/></bestwith> </coffee> </xsl:template> </xsl:stylesheet> The XML produced from the transformation is as follows : <?xml version="1.0" encoding="utf-8"?> <coffee> <taste>Curiously Mild And Bland</taste> <price currency="$US">11.99</price> <availability>Year-round</availability> <bestwith>Curiously Mild And Bland</bestwith> </coffee>
Using xsl:attribute
The xsl:attribute can also be used to create an attribute. In the following example, I am creating a new salesevent element as a child of the coffee element, which has quarter , usregion , and supplier attributes:
<!-- coffee-addattribute_inst.xsl --> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <!-- Add attribute using xsl:attribute instruction --> <xsl:template match="coffee"> <coffee> <taste><xsl:value-of select="taste"/></taste> <price currency="$US"><xsl:value-of select="price"/></price> <availability><xsl:value-of select="availability"/></availability> <bestwith><xsl:value-of select="taste"/></bestwith> <xsl:element name="salesevent"> <xsl:attribute name="quarter">Q3</xsl:attribute> <xsl:attribute name="usregion">New England</xsl:attribute> <xsl:attribute name="supplier">Horacio Zeeman</xsl:attribute> </xsl:element> </coffee> </xsl:template> </xsl:stylesheet> The result is shown here:
<?xml version="1.0" encoding="utf-8"?> <coffee> <taste>Curiously Mild And Bland</taste> <price currency="$US">11.99</price> <availability>Year-round</availability> <bestwith>Curiously Mild And Bland</bestwith> <salesevent quarter="Q3" usregion="New England" supplier="Horacio Zeeman"/> </coffee>
|