2010-11-12 69 views
2

问题:我们有字符实体以各种格式来到我们的系统(例如:&&),我们需要将它们转换为标准XML字符实体(&amp < > ' "),然后通过几次单独的转化将它们作为实体来维护。通过多次转换替换和维护字符实体

鉴于XML:

<rootelm> 
<testdata>&amp;apos; &amp;gt; &amp;lt; &amp;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>&amp;quot;</xsl:text> 
</xsl:variable> 
<xsl:variable name="quote2"> 
    <xsl:value-of select="string('&quot;')"/> 
</xsl:variable> 
<xsl:template match="text()[contains(.,'&amp;lt;') or contains(.,'&amp;gt;') or contains(.,'&amp;quot;') or contains(.,'&amp;apos;')]"> 
    <xsl:value-of select='replace(
    replace(
    replace(
    replace(., "&amp;lt;", "&lt;"), 
    "&amp;gt;", 
    "&gt;" 
    ), 
    "&amp;apos;", 
    "&apos;" 
), 
    $quote, 
    $quote2 
) 
    ' /> 
</xsl:template> 
</xsl:stylesheet> 

我怎能撇号的和报价为实体(源系统期望/需要的话) ?

电流输出:

<rootelm> 
    <testdata>' &gt; &lt; "</testdata> 
</rootelm> 

回答

3

使用Character Maps

[定义:一个字符映射允许 特定字符出现在文本 或属性节点在最终结果 树是在 序列化期间由指定的 字符串替换。]

<xsl:character-map name="quotes"> 
    <xsl:output-character character='"' string="&amp;quot;"/> 
    <xsl:output-character character="'" string="&amp;apos;"/> 
</xsl:character-map> 
+0

谢谢,就是这么做的。 – johkar 2010-11-16 14:02:20

+0

@johkar:你很好。 – 2010-11-16 14:09:11