问题:我们的系统中存在各种格式的字符实体(例如:&
和 &
),我们需要将它们转换为标准如果需要,XML 字符实体 (& < > ' "
),然后通过几个单独的转换将它们维护为实体。
给定 XML:
<rootelm>
<testdata>&apos; &gt; &lt; &quot;</testdata>
</rootelm>
和样式表(基于 xsl:character-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>
最佳答案
使用Character Maps :
[Definition: A character map allows a specific character appearing in a text or attribute node in the final result tree to be substituted by a specified string of characters during serialization.]
<xsl:character-map name="quotes">
<xsl:output-character character='"' string="&quot;"/>
<xsl:output-character character="'" string="&apos;"/>
</xsl:character-map>
关于xml - 通过多次变换替换和维护角色实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4169594/