Question

Let's assume I have a simple XML file:

<data>
  <text>Hello world!&lt;br&gt;Nice to see you all!&lt;br&gt;Goodbye!</text>
</data>

Now I want to replace all &lt;br&gt; strings with &#10; strings so the result should be e.g.:

<transformed>
  <text>Hello world!&#10;Nice to see you all!&#10;Goodbye!</text>
</transformed>

How do I do this?

XSL replace functionality is easy to implement (e.g. in http://geekswithblogs.net/Erik/archive/2008/04/01/120915.aspx) but the tricky part is to get the XSL transformer to output those &#10; strings.. I either get invisible normal linefeed or &amp;#10;

Perfect answer would be an XSL template which does the trick.

Was it helpful?

Solution

Use:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/data">
    <transformed>
      <text>
        <xsl:call-template name="string-replace-all">
          <xsl:with-param name="text" select="text" />
          <xsl:with-param name="replace">&lt;br&gt;</xsl:with-param>
          <xsl:with-param name="by">&amp;#10;</xsl:with-param>
        </xsl:call-template>
      </text>
    </transformed>
  </xsl:template>

  <xsl:template name="string-replace-all">
    <xsl:param name="text" />
    <xsl:param name="replace" />
    <xsl:param name="by" />
    <xsl:choose>
      <xsl:when test="contains($text, $replace)">
        <xsl:value-of select="substring-before($text, $replace)" />
        <xsl:value-of select="$by" disable-output-escaping="yes" />
        <xsl:call-template name="string-replace-all">
          <xsl:with-param name="text" select="substring-after($text,$replace)" />
          <xsl:with-param name="replace" select="$replace" />
          <xsl:with-param name="by" select="$by" />
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$text" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

output:

<transformed>
  <text>Hello world!&#10;Nice to see you all!&#10;Goodbye!</text>
</transformed>

NB!:

Set disable-output-escaping attribute to yes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top