html - 如何在 xsl:copy-of 上禁用文本转义
问题描述
我构建了一个机制,将所有<script />
标签放在页面末尾。
它工作得很好,除了 Ampersant&
字符被编码为&
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>
解决方案
script
XSLT 2.0+ 中的 HTML 输出方法不应该对元素中的文本执行转义。
但是,2.0 和 3.0 之间存在差异。在 2.0 中,这只适用script
于没有命名空间的元素。在 3.0 中,只要您输出 HTML5,它也适用script
于 XHTML 命名空间中的元素。
推荐阅读
- java - java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/json/async/NonBlockingJsonParser 同时创建 AmazonSQSAsync 客户端
- r - 为 R 中的拟合点生成多组预测和预测区间
- reactjs - 如何在控制我的 Datepicker 组件时使 placeHolder 可见(值 = dateOfBirth)
- javascript - 如何使用状态机 Phaser 转换到下降状态
- spring - RowCallbackHandler 加载行信息内存
- reactjs - 以状态变量为参数反应自定义钩子
- linux - 如何将工作空间(一个简单的项目)从 Windows 文件系统(/mnt/)移动到 linux(~/home)
- python - 添加对 ctx.author 消息 discord.py 库的反应
- javascript - 寻找数字的最佳子集组合以达到给定的总和或最接近它
- python - 为什么在这种情况下 python 不能绘制我的函数?