在XML文档中必须转义哪些字符,或者在哪里可以找到这样的列表?
当前回答
这取决于上下文。对于内容,它是<和&,和]]>(尽管是一个由三个字符组成的字符串而不是一个字符)。
对于属性值,它是<、&、"和'。
对于CDATA,为[]>。
其他回答
公认的答案不正确。最好是使用一个库来转义xml。
正如在另一个问题中提到的
基本上,控制字符和超出Unicode范围的字符是不允许的。这也意味着,例如,调用字符实体是禁止的。”
如果你只转义这五个字符。您可能会遇到这样的问题:发现了一个无效的XML字符(Unicode: 0xc)
这取决于上下文。对于内容,它是<和&,和]]>(尽管是一个由三个字符组成的字符串而不是一个字符)。
对于属性值,它是<、&、"和'。
对于CDATA,为[]>。
对一个老问题的新的、简化的回答……
简化XML转义(有优先级,100%完成)
Always (90% important to remember) Escape < as < unless < is starting a <tag/> or other markup. Escape & as & unless & is starting an &entity;. Attribute Values (9% important to remember) attr=" 'Single quotes' are ok within double quotes." attr=' "Double quotes" are ok within single quotes.' Escape " as " and ' as ' otherwise. Comments, CDATA, and Processing Instructions (0.9% important to remember) <!-- Within comments --> nothing has to be escaped but no -- strings are allowed. <![CDATA[ Within CDATA ]]> nothing has to be escaped, but no ]]> strings are allowed. <?PITarget Within PIs ?> nothing has to be escaped, but no ?> strings are allowed. Esoterica (0.1% important to remember) Escape control codes in XML 1.1 via Base64 or Numeric Character References. Escape ]]> as ]]> unless ]]> is ending a CDATA section. (This rule applies to character data in general – even outside a CDATA section.)
如果您使用适当的类或库,它们将为您进行转义。许多XML问题都是由字符串连接引起的。
XML转义字符
只有五种:
" "
' '
< <
> >
& &
转义字符取决于使用特殊字符的位置。
这些示例可以在W3C标记验证服务(W3C Markup Validation Service)中验证。
Text
安全的方法是转义文本中的所有五个字符。但是,",'和>这三个字符在文本中不需要转义:
<?xml version="1.0"?>
<valid>"'></valid>
属性
安全的方法是转义属性中的所有五个字符。但是,>字符不需要在属性中转义:
<?xml version="1.0"?>
<valid attribute=">"/>
'字符在属性中不需要转义,如果引号是":
<?xml version="1.0"?>
<valid attribute="'"/>
同样,如果引号是',属性中的"不需要转义:
<?xml version="1.0"?>
<valid attribute='"'/>
评论
注释中不能转义所有5个特殊字符:
<?xml version="1.0"?>
<valid>
<!-- "'<>& -->
</valid>
名为CDATA
所有5个特殊字符都不能在CDATA节中转义:
<?xml version="1.0"?>
<valid>
<![CDATA["'<>&]]>
</valid>
处理指令
在XML处理指令中,所有5个特殊字符都不能转义:
<?xml version="1.0"?>
<?process <"'&> ?>
<valid/>
XML vs. HTML
HTML有自己的一组转义码,可以覆盖更多的字符。
也许这将有所帮助:
XML和HTML字符实体引用列表:
在SGML、HTML和XML文档中 被称为字符的逻辑结构 数据和属性值由 字符序列,其中每个 性格可以直接表现出来 (代表自己),或者可以 由一系列字符表示的 称为字符引用,其中 有两种类型:数字类型 字符引用和一个字符 实体引用。本文列出了 字符实体引用它 在HTML和XML文档中有效。
那篇文章列出了以下五个预定义的XML实体:
quot "
amp &
apos '
lt <
gt >