Get your XML right – Elements vs Attributes

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.

Get your XML right – Elements vs Attributes