XSLT Tutorial
XSLT Elements: xsl:for-each, xsl:attribute
xsl:for-each
- The xsl: for-each instruction allows you to do looping in XSLT
for a given node set..
- As we've seen from a previous example (Worksheet
4, people.xsl), these rows in a HTML table
are processed for each person element in the people
context:
<xsl:for-each select="PEOPLE/PERSON">
<TR>
<TD><xsl:value-of
select="NAME"/></TD>
<TD><xsl:value-of
select="ADDRESS"/></TD>
<TD><xsl:value-of
select="TEL"/></TD>
<TD><xsl:value-of
select="FAX"/></TD>
<TD><xsl:value-of
select="EMAIL"/></TD>
</TR>
</xsl:for-each>
The xsl:attribute allows you to add an attribute to an
element. This element is often used when you need to add a
source(src) to an image. Remembering that in HTML an img tag is
still an element in XML term. So when we are wanting to add any
of these attributes to elements, you need to use this
technique.
In this example we are adding a src attribute to an <img>
tag:
<img>
<xsl:attribute name="src">
<xsl:value-of select="@src" />
</xsl:attribute>
</img>
The output:
<img src="dodaa.gif">
Tip: If you find that the output goes over many lines then
you can either:
- Place the code over one line:
<img><xsl:attribute name="src"><xsl:value-of select="@src" /></xsl:attribute></img>
<img>
<xsl:attribute name="src"><xsl:text/>
<xsl:value-of select="@src" />
</xsl:attribute>
</img>
Attribute Value Template
Using the xsl:attribute element is useful when you want to output an attribute
based on a choice (see the example in the xsl:choose section).
But if you want a simpler way to output an
attribute for an element, you can use the Attribute Value Template, which
uses curley
brackets {} to
surround the XPath expression that you want to ouput in an attribute.
Using the xsl:attribute element is a bit long, so, using the
example above you can use the attribute value template to rather
output:
<img src="{@src}" />
Attribute value templates can only be used with:
- <xsl:attribute>
- <xsl:element>
- <xsl:number>
- <xsl:processing-instruction>
- <xsl:sort>
- and of course all attributes (such as HTML attributes, img, etc)
which do not belong to the XSL namespace.
|