问题:我们的系统中存在各种格式的字符实体(例如:&
and &
),如果需要的话,我们需要将它们转换为标准 XML 字符实体(& < > ' "
),然后通过几个单独的转换将它们维护为实体。
给定 XML:
<rootelm>
<testdata>&apos; &gt; &lt; &quot;</testdata>
</rootelm>
和一个样式表(基于xsl:character-map 来替换特殊字符 https://stackoverflow.com/questions/3207297/xslcharacter-map-to-replace-special-characters):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<!-- COPY EVERYTHING -->
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="@* | node()">
<xsl:sort select="local-name()"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:variable name="quote">
<xsl:text>&quot;</xsl:text>
</xsl:variable>
<xsl:variable name="quote2">
<xsl:value-of select="string('"')"/>
</xsl:variable>
<xsl:template match="text()[contains(.,'&lt;') or contains(.,'&gt;') or contains(.,'&quot;') or contains(.,'&apos;')]">
<xsl:value-of select='replace(
replace(
replace(
replace(., "&lt;", "<"),
"&gt;",
">"
),
"&apos;",
"'"
),
$quote,
$quote2
)
' />
</xsl:template>
</xsl:stylesheet>
如何将撇号和引号保留为实体(源系统期望/需要它)?
电流输出:
<rootelm>
<testdata>' > < "</testdata>
</rootelm>