What's the difference between the two and when should I use each:
<person>
<firstname>Joe</firstname>
<lastname>Plumber</lastname>
</person>
versus
<person firstname="Joe" lastname="Plumber" />
Thanks
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
Element centric
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.
In my company, we would favour the 2nd approach.
The way we think about it is that "firstname" and "lastname" are attributes of the "person" node, rather than sub-fields of the "person" node. It's a subtle difference.
In my opinion the 2nd approach is more concise, and readability/maintainability is significantly improved, which is very important.
Of course it would depend on your application. I don't think there is a blanket rule that covers all scenarios.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With