我需要在XML文档中转义哪些字符? [英] What characters do I need to escape in XML documents?

查看:274
本文介绍了我需要在XML文档中转义哪些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

如果您使用适当的班级或图书馆,他们会为你逃跑。许多XML问题是由字符串连接造成的。



XML转义字符



只有五个:

 & quot; 
'&
<
> ;& gt;
& amp; amp; amp; amp; amp;

转义字符取决于使用特殊字符。



这些示例可以在 W3C标记验证服务



文本



安全的方法是将所有五个字符文本,但是,三个字符'> 不需要转义文本:

 <?xml version =1.0?> 
< valid>'>< / valid>



属性



安全的方法是转义属性中的所有五个字符,但是,> 字符不需要在属性中转义:

 <?xml version =1.0?> 
< valid attribute => />

' character needn'如果报价是

  ?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>



处理说明



所有5个特殊字符不得在XML处理指令中进行转义:

 <?xml version =1.0? > 
<?process<&>?>
< valid />



XML与HTML



HTML具有其自己的一组转义码,其中涵盖了更多的字符。


What characters must be escaped in XML documents, or where could I find such a list?

解决方案

If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation.

XML escape characters

There are only five:

"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

Escaping characters depends on where the special character is used.

The examples can be validated at W3C Markup Validation Service.

Text

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='"'/>

Comments

All 5 special characters must not be escaped in comments:

<?xml version="1.0"?>
<valid>
<!-- "'<>& -->
</valid>

CDATA

All 5 special characters must not be escaped in CDATA sections:

<?xml version="1.0"?>
<valid>
<![CDATA["'<>&]]>
</valid>

Processing instructions

All 5 special characters must not be escaped in XML processing instructions:

<?xml version="1.0"?>
<?process <"'&> ?>
<valid/>

XML vs. HTML

HTML has its own set of escape codes which cover a lot more characters.

这篇关于我需要在XML文档中转义哪些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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