如何在 XML 属性值中转义双引号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3961505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 13:21:11  来源:igfitidea点击:

How can I escape double quotes in XML attributes values?

xml

提问by Jader Dias

From the following trials

从以下试验

<tag attr="\"">
<tag attr="<![CDATA["]]>">
<tag attr='"'>

Only the last one works for an XML parser that I'm using here. Is there an alternative?

只有最后一个适用于我在这里使用的 XML 解析器。有替代方案吗?

回答by Sachin Shanbhag

You can use &quot;

您可以使用 &quot;

回答by Wim Coenen

From the XML specification:

XML 规范

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "&apos;", and the double-quote character (") as "&quot;".

为了允许属性值同时包含单引号和双引号,撇号或单引号字符 (') 可以表示为 "'",双引号字符 (") 可以表示为 """。

回答by kjhughes

A double quote character (") canbe escaped as &quot;, but here's the rest of the story...

双引号字符 ( ")可以转义为&quot;,但这是故事的其余部分......

Double quote character mustbe escaped in this context:

在这种情况下必须转义双引号字符:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    
  • 在由双引号分隔的 XML 属性中:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Double quote character need notbe escaped in most contexts:

在大多数情况下,双引号字符不需要转义:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Similarly, (') require no escaping if (") are used for the attribute value delimiters:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    
  • 在 XML 文本内容中:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • 在由单引号 ( ')分隔的 XML 属性中:

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    类似地,'如果 ( ") 用于属性值分隔符, ( ) 不需要转义:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

See also

也可以看看

回答by Kenny Evitt

The String conversionpage on the Coder's Toolboxsite is handy for encoding more than a small amount of HTML or XML code for inclusion as a value in an XML element.

字符串转换页面上的编码器的工具箱网站是非常方便的比HTML少量或XML代码包含在一个XML元素的值编码的更多。