【发布时间】:2021-03-03 21:36:07
【问题描述】:
我构建了一个机制,将所有<script /> 标签放在页面末尾。
效果很好,只是 Ampersant &amp; 字符被编码为 &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 &
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>
【问题讨论】:
-
让 XSLT 使用嵌入式脚本构造文本/html 输出可能会很棘手。目前您还没有明确说明您的目标结果应该是什么,HTML 4、HTML5、XHTML 5?您使用哪种 XSLT 处理器?
-
我正在使用 HTML5 和 saxon9-9.0.0.8