Element content to attribute

Almost as common as attribute value copy-through is the need to convert an element value to an attribute value. For example, in the source document the text to display if the image cannot be presented may be stored in the Image element, as element content:

<image name="boat.gif" y="60mm" x="40mm">
Picture of a boat.
</image>

In the HTML IMG element, this text needs to appear in the ALT attribute:

<IMG SRC="boat.gif" ... ALT="Picture of a boat."/>

The expression language makes this transformation almost as simple as copying-through attribute values. In this case, the value required is the text content of the element. The text node within the current element is represented by the 'text()' function:

<xsl:template match="image">
  <IMG ALT="{text()}" ... />
</xsl:template>

However, this approach is not infallible. The source element may contain child elements instead of (or as well as) directly containing text. The method shown above finds the first text block contained directly within the source element, if there is one, and ignores everything else. On the other hand, it would not be appropriate to copy child elements into the output attribute. The solution is to return the value of the current element ('.') (which means the concatenated values of all embedded text nodes):

   <image ...>Picture of a <bold>BIG</bold> boat.</image>


<xsl:template match="image">
  <IMG ALT="{.}" ... />
</xsl:template>


   <IMG ... ALT="Picture of a BIG boat."/>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset