Creates an attribute node and attaches it to an output element.
<xsl:attribute name = "attribute-name" namespace = "uri-reference"> </xsl:attribute>
Number of occurrences | Unlimited |
Parent elements | xsl:copy, xsl:element, xsl:for-each, xsl:if, xsl:otherwise, xsl:param, xsl:template, xsl:variable, xsl:when, xsl:with-param |
Child elements | xsl:apply-templates, xsl:choose, xsl:copy, xsl:copy-of, xsl:for-each, xsl:if, xsl:if, xsl:text, xsl:variable |
The contents of this element specify the value of the attribute.
Attributes can be added or modified during transformation by placing the <xsl:attribute> element within elements that generate output, such as the <xsl:copy> element. Note that <xsl:attribute> can be used directly on output elements and not only in conjunction with <xsl:element>.
All attributes must be applied before children are added to the element.
This example generates an attribute that obtains its value from the XML source. It generates output in the form <IMG src="value-from-XML-source"/>, using an XPath expression that retrieves the appropriate data from the XML source—here, "imagenames/imagename".
<IMG> <xsl:attribute name="src"> <xsl:value-of select="imagenames/imagename" /> </xsl:attribute> </IMG>
This example copies the "myElement" element and adds a "copied" attribute with the value "true".
<xsl:template match="myElement"> <xsl:copy> <xsl:attribute name="copied">true</xsl:attribute> <xsl:apply-templates /> </xsl:copy> </xsl:template>
The following samples demonstrate how to use attribute value templates to use content in the XML source document as the name of an attribute:
Attribute.xml
<?xml version="1.0"?> <investment> <type>stock</type> <name>Microsoft</name> <price type="high">100</price> <price type="low">94</price> </investment>
attribute.xsl
<?xml version='1.0'?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes"/> <xsl:template match="investment"> <xsl:element name="{type}"> <xsl:attribute name="name" ><xsl:value-of sselect="name"/></xsl:attribute> <xsl:for-each select="price"> <xsl:attribute name="{@type}" ><xsl:value-of sselect="."/></xsl:attribute> </xsl:for-each> </xsl:element> </xsl:template> </xsl:stylesheet>
XSLT Output (viewed with the XSLT viewer):
<?xml version="1.0" encoding="UTF-16"?> <stock name="Microsoft" high="100" low="94"/>
Accessing and Outputting Attributes | Generating More Sophisticated Output