Working with Attribute Value Templates

 
xslt for dummies
Chapter 4 - Templates Rule!
XSLT For Dummies
by Richard Wagner
Hungry Minds 2002
  

When your result document is XML or HTML format, you often have an occasion to plug in the result of an XPath expression as the value of an attribute. Designed specifically for this purpose, an attribute value template is located inside a template and surrounded by curly braces ({}).

For example, suppose I use the following XML snippet as the source:

 <score> <film>A Little Princess</film> <composer>Patrick Doyle</composer> <year>1995</year> <grade>100</grade> </score> 

If I convert each of the score s child elements to attributes of the score element, the end result looks like this:

 <score year="1995" grade="100" composer="Patrick Doyle" film="A Little Princess"/> 

To perform this transformation, I start by writing a new element as literal text in my template rule, putting empty quotes as the values:

 <score year="" grade="" composer="" film=""/> 

Using attribute value templates, I then enclose the name of each child node in curly braces. The curly braces tell the XSLT processor to evaluate whats inside each of them as an expression:

 <xsl:template match="score"> <score year="{year}" grade="{grade}" composer="{composer}" film="{film}"/> <xsl:apply-templates/> </xsl:template> <xsl:template match="film"/> <xsl:template match="composer"/> <xsl:template match="year"/> <xsl:template match="grade"/> 

As you can see, I also defined empty template rules for the child elements to remove them from the result tree. If I dont explicitly define these empty template rules, they are added as attributes (through the attribute value templates) and their text nodes (through xsl:apply-templates ) are also added.

  
 
 
2000-2002    Feedback


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

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