XML best practices: attributes vs additional elements

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.

Attribute centric

  • Smaller size than element centric.
  • Not very interoperable, since most XML parsers will think the user data is presented by the element, Attributes are used to describe the element.
  • There is no way to present nullable value for some data type. e.g. nullable int
  • Can not express complex type.

Element centric

  • Complex type can be only presented as an element node.
  • Very interoperable
  • Bigger size than attribute centric. (Compression can be used to reduce the size significantly.)
  • Nullable data can be expressed with attribute xsi:nil="true"
  • Faster to parse since the parser only looks to elements for user data.

Practical

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.

Background

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


Sometime in the future when you add an <address> property, you won't want to make it an XML attribute. This is because an <address> might be a more complex element made up of street address, city, country, etc.

For this reason, you may want to choose the first subelement form unless you're really sure that the attribute won't need to go much deeper. The first form allows for greater extensibility in the future.

If you're at all concerned about space, compress your XML.

Tags:

Xml