Tuesday, 7 June 2011

XSLT - Adding an attribute to an element based on XML data

Adding an attribute to an element requires us to utilise the xsl:attribute element.

Consider the following example:
  <xsl:attribute name="src">
    <xsl:value-of select="imageURL" />
  <xsl:attribute name="alt">
    <xsl:value-of select="altText" />

This will add an src and an alt attribute to an img element; based on the values within the imageURL and altText elements in the XML in this example.

Note: You must make sure that the attributes are added within the element itself. I.e. If the img tag is closed before the attributes are added in the above example, then this would be invalid.

No comments: