我需要在 XML 文档中转义哪些字符? [英] What characters do I need to escape in XML documents?
问题描述
XML 文档中哪些字符必须转义,或者在哪里可以找到这样的列表?
What characters must be escaped in XML documents, or where could I find such a list?
推荐答案
如果您使用合适的类或库,它们会为您进行转义.许多 XML 问题都是由字符串连接引起的.
If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation.
只有五个:
" "
' '
< <
> >
& &
转义字符取决于特殊字符的使用位置.
Escaping characters depends on where the special character is used.
这些示例可以在 W3C 标记验证服务进行验证.
The examples can be validated at the W3C Markup Validation Service.
安全的方法是转义文本中的所有五个字符.但是,三个字符 "
、'
和 >
不需要在文本中转义:
The safe way is to escape all five characters in text. However, the three characters "
, '
and >
needn't be escaped in text:
<?xml version="1.0"?>
<valid>"'></valid>
属性
安全的方法是转义属性中的所有五个字符.但是,>
字符不需要在属性中转义:
Attributes
The safe way is to escape all five characters in attributes. However, the >
character needn't be escaped in attributes:
<?xml version="1.0"?>
<valid attribute=">"/>
如果引号是 "
,则 '
字符不需要在属性中转义:
The '
character needn't be escaped in attributes if the quotes are "
:
<?xml version="1.0"?>
<valid attribute="'"/>
同样,如果引号是 '
,则 "
不需要在属性中转义:
Likewise, the "
needn't be escaped in attributes if the quotes are '
:
<?xml version="1.0"?>
<valid attribute='"'/>
评论
所有五个特殊字符不得在评论中转义:
<?xml version="1.0"?>
<valid>
<!-- "'<>& -->
</valid>
CDATA
所有五个特殊字符不得在CDATA部分转义:
<?xml version="1.0"?>
<valid>
<![CDATA["'<>&]]>
</valid>
处理说明
所有五个特殊字符不得在 XML 处理指令中转义:
Processing instructions
All five special characters must not be escaped in XML processing instructions:
<?xml version="1.0"?>
<?process <"'&> ?>
<valid/>
XML 与 HTML
HTML 有它自己的一组转义码,涵盖了更多的字符.
这篇关于我需要在 XML 文档中转义哪些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!