我需要替换 XML 正文中的双引号/单引号吗? [英] Do I need to replace double/single quote in XML body text?

查看:40
本文介绍了我需要替换 XML 正文中的双引号/单引号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果它关闭,请在此处更正我的术语:

Please correct my terminology here if it's off:

XML 的 5 个字符替换是:

The 5 character substitutions for XML are:

  • &( & )
  • &lt;( < )
  • &gt;( > )
  • &quot;( " )
  • &’;( ' )

所有这些替换都需要在元素文本中发生吗?还是只有属性文本?(术语更正?)

Do all of these substitutions need to happen in a element text? Or only attribute text? (terminology correction?)

例如这是有效的 XML 吗?

e.g. is this valid XML?

<myelement>x && y</myelement>
<myelement>And I quote, "no"</myelement>

&gt;&lt; 在这种情况下似乎很明显可以替换,但我不清楚替换规则是否对整个 XML 是全局的文档,或者它们是否适用于文档的不同部分(例如,cdata 部分应用不同的规则).

&gt; and &lt; seem obvious to replace in this context, but I'm not clear if the replacement rules are global for the entire XML document, or if they apply differently to different parts of the document (example, cdata sections apply different rules).

假设:这是无效的 XML:

Assumption: this is invalid XML:

<myelement field="no & allowed here"/>
<myelement field="no <> allowed here"/>

引号是属性的明显分隔符,<>是元素文本的明显分隔符.

Quotes are obvious delimiters of attributes, and <> are obvious delimiters of element text.

推荐答案

在元素内容中你只需要转义 &<;你永远不需要转义单引号或双引号,并且只有当它出现在序列 ]]> 中时你才需要转义 >(许多人无条件地替换它,因为那更简单).

In element content you only need to escape & and <; you never need to escape single or double quotes, and you need to escape > only if it appears as part of the sequence ]]> (many people replace it unconditionally, because that's simpler).

在属性内容中,您只需要转义 &< 以及 '",取决于使用哪个作为属性分隔符.

In attribute content you only need to escape & and < and either ' or ", depending which one was used as the attribute delimiter.

& 开头的实体在注释或 CDATA 部分、元素或属性名称中无法识别,因此在这些上下文中不得对特殊字符进行转义.

Entities starting with & are not recognized in comments or CDATA sections, or in element or attribute names, so special characters must not be escaped in those contexts.

这篇关于我需要替换 XML 正文中的双引号/单引号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆