首页 > 解决方案 > 如何在 xsl:copy-of 上禁用文本转义

问题描述

我构建了一个机制,将所有<script />标签放在页面末尾。

它工作得很好,除了 Ampersant&字符被编码为&amp;JavaScript 代码中的字符,这不是我想要的。

我该如何解决这个问题?

XML

<?xml version="1.0" encoding="UTF-8"?>
<root></root>

XSLT

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="2.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" />
    
    <xsl:template match="*">
        <xsl:variable name="body">
            <xsl:apply-templates select="." mode="body"></xsl:apply-templates>
        </xsl:variable>
        
        <xsl:apply-templates select="$body" mode="no-script" />
        
        <xsl:copy-of select="$body//script" xpath-default-namespace="http://www.w3.org/1999/xhtml" />
    </xsl:template>
    
    <xsl:template match="script" mode="no-script">
        
    </xsl:template>
    
    <xsl:template match="*[not(self::script)] | @* |comment()" mode="no-script">
        <xsl:if test="name() != 'script'">
            <xsl:copy xpath-default-namespace="http://www.w3.org/1999/xhtml">
                <xsl:apply-templates select="node()[not(self::script)] | @*" mode="no-script" />
            </xsl:copy>
        </xsl:if>
    </xsl:template>

    <xsl:template match="*" mode="body">
        <script type="text/javascript">
            // Ampersand <xsl:text disable-output-escaping="yes"><![CDATA[&]]></xsl:text>
            var a = 'a';
        </script>
        <div>Hello World</div>
    </xsl:template>
</xsl:stylesheet>

它输出:

<div xmlns="http://www.w3.org/1999/xhtml">Hello World</div>
<script xmlns="http://www.w3.org/1999/xhtml" type="text/javascript">
            // Ampersand &amp;
            var a = 'a';
        </script>

我试过了,但我想知道是否有办法将<script>标签保留在变量中$body

<script type="text/javascript">
  <xsl:value-of select="$body//script" xpath-default-namespace="http://www.w3.org/1999/xhtml" disable-output-escaping='yes'/>
</script>

标签: htmlxmlxslt

解决方案


scriptXSLT 2.0+ 中的 HTML 输出方法不应该对元素中的文本执行转义。

但是,2.0 和 3.0 之间存在差异。在 2.0 中,这只适用script于没有命名空间的元素。在 3.0 中,只要您输出 HTML5,它也适用script于 XHTML 命名空间中的元素。


推荐阅读