Why would I use select='text()'

<xsl:value-of select='text() /> is used when you want to select the text embedded between the opening and closing tag of the current element. However, in this context, the text() function selects only the first child text node. If you want to:

  • select all embedded text (including text within the child elements), use <xsl:value-of select='.' /> as this renders the whole tree of descendants as a text string;
  • select all text nodes within the current element but no text in descendant elements, use a <xsl:for-each select='text()' > loop.
For example, the following XML document ...
<?xml version="1.0" ?>
<?xml-stylesheet href="t1.xsl" type="text/xsl"?>
  <row>Before <b>an embedded tag</b> and after it</row>
... transformed with this stylesheet ...
<?xml version="1.0" encoding="windows-1250" ?>
<xsl:output method="text" encoding="windows-1250" />

<xsl:template match="row">
  Text(): <xsl:value-of select="text()" />
  Current element: <xsl:value-of select="." />
  Text loop: <xsl:for-each select="text()"><xsl:value-of select="." /></xsl:for-each>

... results in the following text:

Text(): Before
Current element: Before an embedded tag and after it
Text loop: Before and after it

This post is part of You've asked for it series of articles.

No comments:

Post a Comment