1

Suppose the following input xml:

<div text="This is [BFboldBF]">
</div>

The goal is to transform this into this:

 <div>
      This is <span class="bold">bold</span> text
 </div>

My xsl has the following setting:

<xsl:output method="html" encoding="utf-8" indent="no" omit-xml-declaration="yes" />

I tried substitution via the replace function

<xsl:variable name="lfL">
  <xsl:text>&lt;span class="bold"&gt;</xsl:text>
</xsl:variable>

<xsl:variable name="close">
  <xsl:text>&lt;span/&gt;</xsl:text>
</xsl:variable>

<xsl:variable name="text" select="@text"/>
<xsl:variable name="lfBT" select="replace($text, '\[BF', $lfL)"/>
<xsl:variable name="rfBT" select="replace($lfBT, 'BF\]', $close)"/>

and rendering the text variable via

<div>
  <xsl:value-of select="$text" disable-output-escaping="yes"/>
</div>

this however does not render the xml. Instead it renders it as plain text, with the brackets escaped '&lt';

1
  • The use of replace suggests you have XSLT 2 or 3 so in any case, if your task is to analyze/process/parse plain text but to construct nodes like span or b elements, use xsl:analyze-string (in XSLT 2 or 3) or the function analyze-string (in XSLT 3) instead of replace. Commented Feb 14, 2022 at 21:26

1 Answer 1

1

Try to avoid disable-output-escaping, because it won't work in all environments. Not all XSLT processors support it, and some support it only if you run the transformation in a particular way. That's because it requires some out-of-band communication between the XSLT processor and the serializer.

The way to do this is analyse-string:

<xsl:template match="div[@text]">
  <div>
    <xsl:analyse-string select="@text" regex="\[BF(.*)BF\]">
      <xsl:on-match>
        <bold><xsl:value-of select="regex-group(1)"/></bold>
      </xsl:on-match>
      <xsl:on-no-match>
        <xsl:value-of select="."/>
      </xsl:on-no-match>
    </xsl:analyze-string>
  </div>
</xsl:template>

Not tested.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.