简体   繁体   English

xsl:character-map替换特殊字符

[英]xsl:character-map to replace special characters

Given an element with a value of: 给定一个元素,其值为:

 <xml_element>Distrib = SU &amp; Prem &amp;lt;&amp;gt; 0</xml_element>

I need to turn &amp;lt; 我需要转动&amp;lt; or &amp;gt; &amp;gt; into &lt; 进入&lt; or &gt; &gt; because a downstream app requires it in this format throughout the entire XML document. 因为下游应用在整个XML文档中都要求采用这种格式。 I would need this for quotes and apostrophes too. 我也需要用引号和撇号。 I am tryinging a character-map in XSLT 2.0. 我正在尝试XSLT 2.0中的字符映射。

<xsl:character-map name="specialchar">
    <xsl:output-character character="&apos;" string="&amp;apos;" />
    <xsl:output-character character="&quot;" string="&amp;quot;" />
    <xsl:output-character character="&gt;" string="&amp;gt;" />
</xsl:character-map>

The <xsl:character-map> instruction can be used to serialize a single character to any string. <xsl:character-map>指令可用于将单个字符序列化为任何字符串。 However this problem requires more than one character (an ampersand followed by another character to be replaced. 但是,此问题需要一个以上的字符(“&”号后跟另一个字符才能被替换。

<xsl:character-map> cannot be used to solve such problems. <xsl:character-map>不能用于解决此类问题。

Here is a solution to this problem, using the XPath 2.0 replace() function: 这是使用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(., "&amp;lt;", "&lt;"),
                "&amp;gt;",
                "&gt;"
                ),
        "&amp;apos;",
        "&apos;"
        )
    '/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the following XML document : 当此转换应用于以下XML文档时

<xml_element>Distrib = SU &amp; &amp;apos;Prem &amp;lt;&amp;gt; 0</xml_element>

the wanted result is produced : 产生想要的结果

<xml_element>Distrib = SU &amp; 'Prem &lt;&gt; 0</xml_element>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM