何时到CDATA vs. Escape&反之亦然? [英] When to CDATA vs. Escape & Vice Versa?

查看:114
本文介绍了何时到CDATA vs. Escape&反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用从数据库中提取的值创建XML文档。有时候由于旧版实现,我会撤销一个包含一个没有正确转义的字符无效的值(例如& amp;)。



所以问题就是,我应该是CDATA还是Escape?某些情况是否比较适合?



示例:

 <电子邮件与GT; FOO&安培; bar@domain.com< /电子邮件与GT; 

我在这里倾向于CDATA。

 < Name> Bob&汤姆与LT; /名称> 

我倾向于在这里逃离。



我想避免盲目地CDATA的每一次,但从性能的角度看,这似乎是合乎逻辑的选择。这将总是比寻找无效的char更快,如果它存在然后换行。



想法?

解决方案

CDATA对于人的可读性主要是有用的,IMO。就机器而言,CDATA和转义文本之间的距离最大不同于长度。或许这个转义的版本需要一点时间才能处理,但是我也可以这样说,因为除非你的应用程序主要是IO绑定,否则这不应该是一个重要的因素。



人们有可能正在阅读XML吗?如果没有,只需让XML解析器做它所做的,不用担心CDATA vs转义文本。如果人们会阅读这个XML,那么也许CDATA可以是更好的选择。



如果你要有一个XML元素,其值是XML,那么例如,CDATA可能是更好的选择。



有关更多信息,请参阅XML常见问题的问题,例如什么时候应该使用CDATA标记节?


I'm creating XML documents with values fetched from a DB. Occasionally due to a legacy implementation, I'll pullback a value that contains a char that's invalid when not properly escaped (& for example).

So the question becomes, should I CDATA or Escape? Are certain situations more appropriate for one vs. the other?

Examples:

<Email>foo&bar@domain.com</Email>

I'd lean towards CDATA here.

<Name>Bob & Tom</Name>

I'd lean towards escaping here.

I want to avoid blindly CDATA'ing every time, but from a performance perspective it seems like that's the logical choice. That will be always faster than looking for an invalid char, and if it exists then wrap.

Thoughts?

解决方案

CDATA is primarily useful, IMO, for human readability. As far as a machine is concerned, there's no difference between CDATA and escaped text other than the length, at most. Perhaps the escaped version will take a little bit longer to process, but I say perhaps, because this shouldn't be a significant factor unless your application is mostly IO-bound.

Are people likely to be reading the XML? If not, just let the XML parser do what it does and don't worry about CDATA vs escaped text. If people will be reading this XML, then perhaps CDATA can be the better choice.

If you're going to have an XML element whose value is XML, then for this case, CDATA may be the better choice.

For more information, see for example the XML FAQ's question, When should I use a CDATA Marked Section?

这篇关于何时到CDATA vs. Escape&amp;反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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