给定一个值为的元素:
<xml_element>Distrib = SU & Prem &lt;&gt; 0</xml_element>
Run Code Online (Sandbox Code Playgroud)
我需要转入&lt;
或&gt;
转入<
或>
因为下游应用程序在整个XML文档中都需要这种格式.我也需要这个用于引号和撇号.我正在尝试XSLT 2.0中的字符映射.
<xsl:character-map name="specialchar">
<xsl:output-character character="'" string="&apos;" />
<xsl:output-character character=""" string="&quot;" />
<xsl:output-character character=">" string="&gt;" />
</xsl:character-map>
Run Code Online (Sandbox Code Playgroud)
该<xsl:character-map>
指令可用于将单个字符序列化为任何字符串.但是,此问题需要多个字符(&符号后跟另一个字符要替换.
<xsl:character-map>
不能用来解决这类问题.
以下是使用XPath 2.0 replace()
函数解决此问题的方法:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select=
'replace(
replace(
replace(., "&lt;", "<"),
"&gt;",
">"
),
"&apos;",
"'"
)
'/>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
当此转换应用于以下XML文档时:
<xml_element>Distrib = SU & &apos;Prem &lt;&gt; 0</xml_element>
Run Code Online (Sandbox Code Playgroud)
产生了想要的结果:
<xml_element>Distrib = SU & 'Prem <> 0</xml_element>
Run Code Online (Sandbox Code Playgroud)