xml - 通过多次变换替换和维护角色实体

标签 xml xslt xslt-2.0

问题:我们的系统中存在各种格式的字符实体(例如:&&),我们需要将它们转换为标准如果需要,XML 字符实体 (& < > ' "),然后通过几个单独的转换将它们维护为实体。

给定 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>

最佳答案

使用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="&amp;quot;"/>   
  <xsl:output-character character="'" string="&amp;apos;"/>
</xsl:character-map>

关于xml - 通过多次变换替换和维护角色实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4169594/

相关文章:

xslt - FOP xslt 中 region-before 和 region-body 之间的相对空间

xml - XSLT 函数返回不同的结果 [Saxon-EE vs Saxon-HE/PE]

xslt - 如何在xsl中引用变量:text element?

xslt - 如何在 Tomcat 中设置 XSLT 2.0?

java - 更改 TextView 样式 Android 应用程序

sql-server - 将 xml 列值包装到外部以进行 xml 路径查询

html - 抓取时如何避免加入来自节点的所有文本

java - 将 Java 文件更改为存储过程

XSLT:将属性复制到子元素中的新元素中

xml - 获取不同层中的所有 <PRO>-标签