I have seen from time to time XML from various examples/tutorials/forums – explanations that are confusing and others that are just plain WRONG! Most of it comes down to the inappropriate use of XML elements and attributes. I also happen to think this is one of the most confusing and ambiguous asepects of XML – but I think if you retain the following knowledge you should have little problems in forming your own correct XML documents.
Always bear in mind that “attribute” is essentially metadata i.e. something that describes something about the data. I think a lot of people get confused with the actual terminology – “attribute”, thinking that the main element should have attribute data e.g.:
<part description="some part" price="£12.34" location="A1B2">
Don’t fall into that trap, it will cause you no end of problems, as W3School explains:
- attributes cannot contain multiple values (child elements can)
- attributes are not easily expandable (for future changes)
- attributes cannot describe structures (child elements can)
- attributes are more difficult to manipulate by program code
- attribute values are not easy to test against a DTD
I can’t think of a reason why you would want to store your data in such a way. The correct way would be to do the following:
<part>
<description>some part</description>
<price>£12.34</price>
<location>A1B2</location>
</part>
Each peice of data is represented in it’s own element tag and not stored as an attribute to some arbitary first element.
The rule to remember is – if it looks like data then store as an element. The next question you are probably thinking is – when should I use attributes then? There are no hard and fast rules – annoying I know, but one possible scenario for using an attribute could be as an ID attribute – something that is not intrinsically part of the data but can be used to help identify or tell you something extra about the data.
Conclusion: Use elements to store data, use attributes to describe something about the data.

4 comments
Comments feed for this article
March 3, 2009 at 8:48 am
Dishia
First blog I read after wakeup from sleep today!
—————————-
Mind Blowing!
July 23, 2009 at 8:11 pm
Graeme
To futher the point of using attributed to describe data, the example above expanded :-
some part
£12.34
A1B2
The Price tag can use attributes to describe the price. ie the currency, and if the price is in pounds or pence (dollars or cents)
some part
1234
A1B2
another part
1234
A1B2
If you had everything as attributes to begin with you would be stuck if you suddenly had to add the currency type in.
July 23, 2009 at 8:15 pm
Graeme
dah – cant post xml!
basically the price tag would look like this
price currency=”GBP” display=”pence”
July 29, 2009 at 1:19 pm
Simon
Indeed – I would agree with you there – definitely a valid use of attributes for XML there! Cheers for the comment.