【问题标题】:Escaped apostrophe in XML attributes, using XSLTXML 属性中的转义撇号,使用 XSLT
【发布时间】:2021-01-12 14:56:31
【问题描述】:

可能很愚蠢,但有没有办法使用 xslt 在 xml 属性中包含转义撇号?

据我了解,像撇号这样的字符在 xml elements 中有效,但在它们的 属性 中无效。结果,我试图在输出中将' 转义为' - 但我遇到了一些麻烦。

我已经尝试了各种方法,例如使用 xsl:text/disable-output-escaping'CDATA(以及其他),而我能得到的最接近的方法是像这样双重转义 & 符号:'

但我认为这意味着我只剩下与符号的字符和单独的文本apos;,而不是我想要的正确的'


输入xml:

<?xml version="1.0" encoding="UTF-8"?>
<boof>
    <moo></moo>
</boof>

当前 XSL

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

    <xsl:template match="/">
        <xsl:apply-templates/>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="moo">
        <xsl:element name="moo">
            <xsl:attribute name="att">&amp;apos;</xsl:attribute>
        </xsl:element>
    </xsl:template>
</xsl:transform>

电流输出

<boof>
    <moo att="&amp;apos;"/>
</boof>

期望的输出

<boof>
    <moo att="&apos;"/>
</boof>

【问题讨论】:

  • 您可以像使用任何其他字符一样在属性值中使用撇号,除非您使用它作为属性值的分隔符而不是双引号。
  • 谢谢!我想我误读了一些我在别处读过的材料——我认为撇号在属性中是完全无效的。
  • 在 XSLT 中,您可以专注于获得正确的(结果树的)结构。 XSLT 处理器将确保其序列化正确。

标签: xml xslt


【解决方案1】:

有没有办法使用 xslt 在 xml 属性中包含转义撇号?

没有。一个字符是否被转义并不重要。

&lt;moo att="'" /&gt;&lt;moo att="&amp;apos;" /&gt; 完全一样。它们描述了相同的节点,一旦文档被解析,它们将无法区分。

如果您的代码依赖于 &amp;apos; 存在,则该代码已损坏,这就是您需要修复的代码。

以下都将产生相同的结果:

<xsl:template match="moo">
    <xsl:element name="moo">
        <xsl:attribute name="att">&apos;</xsl:attribute>
    </xsl:element>
</xsl:template>

或者,简称

<xsl:template match="moo">
    <xsl:element name="moo">
        <xsl:attribute name="att">'</xsl:attribute>
    </xsl:element>
</xsl:template>

或者,甚至更短

<xsl:template match="moo">
    <moo att="'" />
</xsl:template>

【讨论】:

  • 啊,对了,事情就简单多了,谢谢!目前没有特定的损坏代码,我只是想确保我输出的是有效的 xml。我刚刚看到相互矛盾的信息表明 ' 字符无效,例如第一个答案 here。我现在可以看到,只有在不使用相同类型的字符时才“强烈建议”。
  • @Mal ' 字符在任何地方都有效,但用单引号括起来的属性除外(att='...&amp;apos;...' 编码 ...'...)。这同样适用于" 字符(att="...&amp;quot;..." 编码..."...)。转义序列&amp;apos;&amp;quot; 仅在这些情况下才真正需要。但当然,它们在任何地方都有效,因此您不会在每次想要引用单引号时使用 &amp;apos; 使您的文档无效。 XSLT 处理器决定它是在属性中使用文字还是转义变体。不会搞砸的。
猜你喜欢
  • 2018-09-21
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2010-10-13
  • 2011-05-23
  • 2016-03-23
  • 2019-06-29
相关资源
最近更新 更多