在XSLT 1.0中用HTML替换字符串

时间:2016-03-18 17:37:27

标签: xml xslt

我正在尝试用&#xA;替换换行符(<br />)。但是,我无法显示实际的<br />标记。

调用:

<xsl:variable name="br"><br /></xsl:variable>
<xsl:call-template name="string-replace-all">
    <xsl:with-param name="text" select="@SolutionNote" />
    <xsl:with-param name="replace" select="'&#xA;'" />
    <xsl:with-param name="by" select="$br" />
</xsl:call-template>

string-replace-all取自this问题中给出的答案(粘贴在此处以供快速参考):

<xsl:template name="string-replace-all">
    <xsl:param name="text" />
    <xsl:param name="replace" />
    <xsl:param name="by" />
    <xsl:choose>
        <xsl:when test="$text = '' or $replace = ''or not($replace)" >
            <!-- Prevent this routine from hanging -->
            <xsl:value-of select="$text" />
        </xsl:when>
        <xsl:when test="contains($text, $replace)">
            <xsl:value-of select="substring-before($text,$replace)" />
            <xsl:value-of select="$by" />
            <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>

使用字符串文字而不是$br进行测试,确认确实存在被替换的内容。换行也不见了 - 只是换成了看似没什么。声明/使用br变量的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

问题在于这一行:

<xsl:value-of select="$by" />

这是因为xsl:value-of输出所选内容的文本值。在这种情况下,如果这是XSLT 1.0,则$by变量实际上是结果树片段。

您需要做的是改为使用xsl:copy-of

<xsl:copy-of select="$by" />