【问题标题】:Escape Character to xml conversion转义字符到 xml 转换
【发布时间】:2014-04-10 06:15:27
【问题描述】:

我的要求是这样的

输入:-

<request> <attribute> <attributeName>Name</attributeName> <attributeValue>a &amp; b</attributeValue> </attribute> <attribute> <attributeName>Name1</attributeName> <attributeValue>b</attributeValue> </attribute> </request>

输出:-

<request> <attribute> <attributeName>Name</attributeName> <attributeValue>a & b</attributeValue> </attribute> <attribute> <attributeName>Name1</attributeName> <attributeValue>b</attributeValue> </attribute> </request>

转义字符可以出现在 n 个标签中,我需要在运行时全部替换,因为属性元素类型是无限的。 我怎样才能在 xslt 中达到同样的效果???

【问题讨论】:

  • 所需的输出格式不正确。 XML 中不能有未转义的 & 字符。
  • 对不起@mzjn,但我不同意你的观点。 &lt;xsl:text disable-output-escaping="yes"&gt;&lt;![CDATA[&amp;]]&gt;&lt;/xsl:text&gt;
  • @NickG:当然,您可以使用 CDATA 部分转义字符。但是问题中给出的想要的输出有一个裸 & 符号,这使得它格式不正确。
  • @NickG 是的,这将“工作” - 除了输出不是 XML。
  • 是的,你是 100% 正确的。 @user3384223 需要的输出不是格式良好的 XML。幸运的是,user3384223 不需要格式良好的 XML(从输出示例判断)。

标签: xml xslt xml-parsing escaping xml-serialization


【解决方案1】:

这会产生你想要的输出! (如果没有,请告诉我!)

identity 模板,复制所有元素。

ampText模板,查找所有包含&amp;amp;的文本

letters 模板迭代(递归)文本中的所有字母,并将所有&amp;amp; 实例替换为&amp;

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 >
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />

<xsl:template name="identity" match="* | @*">
    <xsl:copy>
        <xsl:apply-templates select="* | @* | text()" />
    </xsl:copy>
</xsl:template>

<xsl:template name="ampText" match="text()[contains(.,'&amp;')]">
    <xsl:call-template name="letters">
        <xsl:with-param name="text" select="." />
    </xsl:call-template>
</xsl:template>

<xsl:template name="letters">
  <xsl:param name="text" select="'Some text'" />
  <xsl:if test="$text != ''">
    <xsl:variable name="letter" select="substring($text, 1, 1)" />
    <xsl:choose>
        <xsl:when test="$letter = '&amp;'">
            <xsl:text disable-output-escaping="yes"><![CDATA[&]]></xsl:text>
        </xsl:when>
        <xsl:otherwise><xsl:value-of select="$letter" /></xsl:otherwise>
    </xsl:choose>
    <xsl:call-template name="letters">
      <xsl:with-param name="text" select="substring-after($text, $letter)" />
    </xsl:call-template>
  </xsl:if>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 谢谢尼克,它成功了。感谢大家的善意和最佳回应。
猜你喜欢
  • 2019-05-09
  • 1970-01-01
  • 2010-11-11
  • 2011-05-08
  • 2011-05-26
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多