Alex Rivera | Logout

XSLT Remove leading and trailing whitespace of all attributes

Asked 2013-05-15T19:14:42.060
11

How can I create an identical XML sheet, but with the leading and trailing whitespaces of each attribute removed? (using XSLT 2.0)

Go from this:

<node id="DSN ">
    <event id=" 2190 ">
        <attribute key=" Teardown"/>
        <attribute key="Resource "/>
    </event>
</node>

To this:

<node id="DSN">
    <event id="2190">
        <attribute key="Teardown"/>
        <attribute key="Resource"/>
    </event>
</node>

I suppose I'd prefer to use the normalize-space() function, but whatever works.

Edit
Report

1 Answer

21

normalize-space() will not only remove leading and trailing whitespace, but it will also install a single space character in place of any sequence of consecutive whitespace characters.

A regular expression can be used to handle just leading and trailing whitespace:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

  <xsl:template match="node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@*">
    <xsl:attribute name="{local-name()}" namespace="{namespace-uri()}">
      <xsl:value-of select="replace(., '^\s+|\s+$', '')"/>
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>
answered 2013-05-15T19:58:39.383

Your Answer