xsl:function如何返回包含html标记的字符串值

Mae*_*o13 2 html xslt function xslt-2.0

我试图将java函数转换为xsl:function规范.该函数基本上将html标记放在子字符串周围.我现在遇到了困难:使用java内联代码这很有效,但我无法弄清楚在使用xsl:function时如何防止输出转义.如何实现输出以包含所需的html标记?

我想要实现的一个简化示例如下:输入参数值"AB"应该导致字符串A <b> B </ b>,在html浏览器中显示为A B当然.

我试过的示例功能如下; 但随后得到的字符串是A< b> B</b> (请注意,我必须添加空格以防止实体在此编辑器中被解释),这当然会在浏览器中显示为A <b> B </ b>.

请注意,xsl:element不能在xsl:function代码中使用,因为它没有任何效果; 我希望函数调用的字符串结果包含<和>字符,然后将字符串结果添加到输出结果文件.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:custom="http://localhost:8080/customFunctions">

    <xsl:output method="html" version="4.0" encoding="UTF-8" indent="yes"/>

    <xsl:function name="custom:test">
        <xsl:param name="str"/> 

        <xsl:value-of select="substring($str,1,1)"/>
        <xsl:text disable-output-escaping="yes"><![CDATA[<b>]]></xsl:text>
        <xsl:value-of select="substring($str,2)"/>
        <xsl:text disable-output-escaping="yes"><![CDATA[</b>]]></xsl:text>
    </xsl:function>

    <xsl:template match="/">
        <xsl:element name="html">
            <xsl:element name="body">
                <xsl:value-of select="custom:test('AB')"/>
            </xsl:element>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

Mar*_*nen 6

下面是一个例子,使用序列代替的价值,并确保您的函数返回节点(通常只需书写文字结果元素完成):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:custom="http://localhost:8080/customFunctions"
    exclude-result-prefixes="custom">

    <xsl:output method="html" version="4.0" encoding="UTF-8" indent="yes"/>

    <xsl:function name="custom:test">
        <xsl:param name="str"/> 

        <xsl:value-of select="substring($str,1,1)"/>
        <b>
          <xsl:value-of select="substring($str,2)"/>
        </b>
    </xsl:function>

    <xsl:template match="/">
        <xsl:element name="html">
            <xsl:element name="body">
                <xsl:sequence select="custom:test('AB')"/>
            </xsl:element>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

  • 考虑避免任何禁用输出转义的黑客,你只需要在函数体中创建节点而不是字符串,你需要确保输出函数结果为返回(使用`xsl:sequence`)而不是其字符串值(使用`xsl:value-of'`). (2认同)