adding spaces in XSL transformations

When transforming XML to XHTML documents via XSLT, we occasionally need to create complex strings by joining together values and we will need to separate the values with spaces. For example, given the XML document

<schedule semester="Spring" year="2006">
  <student id="912345678">
    <name>
      <first>John</first>
      <last>John</last>
  </student>
  <testTextContent>Text Content</testTextContent>
  <!-- Omitted the rest of the document for clarity -->
</schedule>


we would like to transform the document in such a way that the title of the resulting HTML document would appear as “John Doe”. In HTML, then, we want the following

<head>
  <title>John Doe</title>
</head>
<body bgcolor="#ffffff">
  <!--  rest omitted  -->
</body>
</html>

At first, you may be tempted to write

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">
  <xsl:template match="/schedule">
    <html>
      <head>
        <title>
          <xsl:value-of select="student/name/@first"/>
          <xsl:value-of select="student/name/@last"/>
          <!--  You wouldn't normally use separate lines
                   but I wanted to avoid line wrap. -->
        </title>
      </head>
    </html>
  </xsl:template>
</xsl:stylesheet>

However, when you apply the above transformation, the title reads "JohnDoe". Essentially, the transformation strips out the whitespace. In order to introduce whitespace, you need to use the XSLT element text:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">
  <xsl:template match="/schedule">
    <html>
      <head>
        <title>
          <xsl:value-of select="student/name/@first"/>
          <xsl:text> </xsl:text> <!-- note the space -->
          <xsl:value-of select="student/name/@last"/>
        </title>
      </head>
    </html>
  </xsl:template>
</xsl:stylesheet>

1 comment:

  1. If you want to add more than one space, or you want to be explicit, you can use:

    &#160;

    It’s the equivalent of   in HTML

    for example:

    <xsl:text>&#160;&#160;&#160;</xsl:text>

    will create three spaces.

    ReplyDelete