xml - XSLT 使用 & 字符验证 CDATA
问题描述
我有一个 CDATA 返回 html 标签的场景,所以我必须使用 disable-output-escaping="yes" 将内容正确呈现到 html 页面。但是,CDATA 也可以包含 & 字符,这导致我的页面无法通过 w3c 验证。
这是我的 xml 源代码的示例:
<?xml version="1.0" encoding="UTF-8"?>
<jobs>
<job>
<positionTitle><![CDATA[Health & Safety Officer]]></positionTitle>
<description1><![CDATA[<p>You must have experience of working in a health & safety team.</p>]]></description1>
</job>
</jobs>
XSLT
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:content="http://purl.org/rss/1.0/modules/content/" >
<xsl:output method="html"/>
<xsl:template match="/">
<xsl:for-each select="jobs/job">
<div class="job">
<div class="title"><h3><xsl:value-of select="positionTitle"/></h3></div>
<div class="description"><xsl:value-of select="description1" disable-output-escaping="yes"/></div>
</div>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
结果是:
<div class="title">
<h3>Health & Safety Officer</h3>
</div>
<div class="description">
<p>You must have experience of working in a health & safety team.</p>
</div>
描述元素中的 & 字符验证失败,如何将其转换&
为&
?
谢谢
解决方案
在XSLT 2.0中,您可以使用该replace()
函数来转义 & 符号:
<xsl:value-of select="replace(description1, '&', '&amp;')" disable-output-escaping="yes"/>
在XSLT 1.0中,您需要改用递归模板:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<xsl:for-each select="jobs/job">
<div class="job">
<div class="title">
<h3>
<xsl:value-of select="positionTitle"/>
</h3>
</div>
<div class="description">
<xsl:call-template name="replace">
<xsl:with-param name="text" select="description1"/>
</xsl:call-template>
</div>
</div>
</xsl:for-each>
</xsl:template>
<xsl:template name="replace">
<xsl:param name="text"/>
<xsl:param name="searchString">&</xsl:param>
<xsl:param name="replaceString">&amp;</xsl:param>
<xsl:choose>
<xsl:when test="contains($text,$searchString)">
<xsl:value-of select="substring-before($text,$searchString)" disable-output-escaping="yes"/>
<xsl:value-of select="$replaceString" disable-output-escaping="yes"/>
<!-- recursive call -->
<xsl:call-template name="replace">
<xsl:with-param name="text" select="substring-after($text,$searchString)"/>
<xsl:with-param name="searchString" select="$searchString"/>
<xsl:with-param name="replaceString" select="$replaceString"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text" disable-output-escaping="yes"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- python - 在数据框中使用 IsolationForest 查找异常值
- bash - 从 bash 脚本运行 wp-cli 会导致路径错误
- java - Android -Permission Denial:编写 com.android.providers.downloads.DownloadStorageProvide
- c# - 从异步任务返回
- java - JDBC Netbeans java+mysql 项目连接语句显示错误,`错误的符号类型:java.lang.Object.getConnection`
- vbscript - 如何使用 asp classic 获取 12 个月前的月份名称?
- python - Openpyxl:工作表没有对象删除行错误
- c++ - 如何使用 Qt 类编译 rpcgen 文件?
- nlp - 公司沟通自然语言分析的流程和进展?
- laravel - Eloquent:获取更改的列