Monday, December 22, 2008

XSLT note 3 - attribute tricks

When you want to output the value of node to destination, you can use <xsl:value-of select="xpath" />. This works only when the destination is not in side of an attribute. If the output is in side of an attribute, you need to use {}. For example.

<xsl:output method="html"/> <xsl:variable name="sortorder">ascending</xsl:variable> <xsl:template match="employees"> <xsl:apply-templates select="employee"> <xsl:sort select="." data-type="text" order="{$sortorder}"/> </xsl:apply-templates> </xsl:template> <xsl:template match="employee"> <a href="{.}"><xsl:value-of select="."/></a> </xsl:template>

If you want to output a attribute of source element, you need to use @attributeName, or attribute::attributeName.

To add an attribute to an output node, you can also use xsl:attribute, like the following.

<xsl:template match="/"> <a> <xsl:attribute name="href">http://google.com</xsl:attribute> <xsl:text>Google</xsl:text> </a> </xsl:template>

Some time we want to convert element to attribute. For example, we want to convert

<Employee> <Name>Fred</Name> <Age>18</Age> </Employee> <Employee Name="Fred" Age="18" />

We can use this template

<xsl:template match="Employee"> <xsl:element name="{name(.)}"> <xsl:for-each select="*"> <xsl:attribute name="{name(.)}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:for-each> </xsl:element> </xsl:template> or <xsl:template match="Employee"> <xsl:copy> <xsl:for-each select="*"> <xsl:attribute name="{name(.)}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:for-each> </xsl:copy> </xsl:template>

No comments:

Post a Comment