O'Reilly logo

Java and XSLT by Eric M. Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Outputting Dynamic Attributes

Let’s assume we have an XML document that lists books in a personal library, and we want to create an HTML document with links to these books on Amazon.com. In order to generate the hyperlink, the href attribute must contain the ISBN of the book, which can be found in our original XML data. An example of the URL we would like to generate is as follows:

<a href="http://www.amazon.com/exec/obidos/ASIN/0596000162">Java and XML</a>

One thought is to include <xsl:value-of select="isbn"/> directly inside of the attribute. However, XML does not allow you to insert the less-than (<) character inside of an attribute value:

<!-- won't work... -->
<a href="<xsl:value-of select="isbn"/>">Java and XML</a>

We also need to consider that the attribute value is dynamic rather than static. XSLT does not automatically recognize content of the href="..." attribute as an XPath expression, since the <a> tag is not part of XSLT. There are two possible solutions to this problem.

<xsl:attribute>

In the first approach, <xsl:attribute> is used to add one or more attributes to elements. In the following template, an href attribute is added to an <a> element:

<xsl:template match="book">
  <li>
    <a>  <!-- the href attribute is generated below -->
      <xsl:attribute name="href">
        <xsl:text>http://www.amazon.com/exec/obidos/ASIN/</xsl:text>
        <xsl:value-of select="@isbn"/>
      </xsl:attribute>
      <xsl:value-of select="title"/>
    </a>
  </li>
</xsl:template>

The <li> tag is used because this is part of a ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required