XML 最佳实践:属性与附加元素 [英] XML best practices: attributes vs additional elements

查看:30
本文介绍了XML 最佳实践:属性与附加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者有什么区别,我应该什么时候使用它们:

What's the difference between the two and when should I use each:

<person>
     <firstname>Joe</firstname>
     <lastname>Plumber</lastname>
</person>

对比

<person firstname="Joe" lastname="Plumber" />

谢谢

推荐答案

有以元素为中心和以属性为中心的 XML,在您的示例中,第一个是以元素为中心的,第二个是以属性为中心.

There are element centric and attribute centric XML, in your example, the first one is element centric, the second is attribute centric.

大多数情况下,这两种模式是等效的,但也有一些例外.

Most of the time, these two patterns are equivalent, however there are some exceptions.

以属性为中心

  • 比以元素为中心的尺寸更小.
  • 互操作性不强,因为大多数 XML 解析器会认为用户数据是由元素呈现的,因此使用属性来描述元素.
  • 无法为某些数据类型提供可为空的值.例如可为空的 int
  • 无法表达复杂类型.

以元素为中心

  • 复杂类型只能作为元素节点呈现.
  • 非常具有互操作性
  • 比以属性为中心的尺寸更大.(压缩可用于显着减小大小.)
  • 可空数据可以用属性 xsi:nil="true" 表示
  • 解析速度更快,因为解析器只查找用户数据的元素.

实用

如果您真的很在意 XML 的大小,请尽可能使用属性(如果合适的话).在需要可为空值、复杂类型或保存大文本值的地方使用元素.如果您不关心 XML 的大小或在传输过程中启用了压缩,请坚持使用元素,因为它们更具可扩展性.

If you really care about the size of your XML, use an attribute whenever you can, if it is appropriate. Use elements where you need something nullable, a complex type, or to hold a large text value. If you don't care about the size of XML or you have compression enabled during transportation, stick with elements as they are more extensible.

背景

在 DOT NET 中,XmlSerializer 可以将对象的属性序列化为属性或元素.在最近的WCF框架中,DataContract序列化器只能将属性序列化为元素,速度比XmlSerializer快;原因很明显,它只需要在反序列化时从元素中查找用户数据即可.

In DOT NET, XmlSerializer can serialize properties of objects into either attributes or elements. In the recent WCF framework, DataContract serializer can only serialize properties into elements and it is faster than XmlSerializer; the reason is obvious, it just needs to look for user data from elements while deserializing.

这里有一篇文章也解释了它元素与属性

Here an article that explains it as well Element vs attribute

这篇关于XML 最佳实践:属性与附加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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