Elements or attributes?

One of the problems when you begin with XML is that you probably don't know where to use attributes and where to use elements or are you using them in the right way. I know I had that problem when I started with XML. There is no such rule that will tell how to use em and that is the reason for all that confusion. Here is one pretty good advice that I found in XML Bible:

  • Use elements for data that is relevant to the reader (meta-data)
  • Use attributes for additional data (IDs, URLs, references...)

After your done with creating document structure ask yourself one question: does the document contains all basic informations even when you remove all tags and attributes? If the answer to this question is yes then you probably created good document.

This is really good advice, but there are some problems and it isn't always the right way to go.

  • Never use attributes when you need to add some structure, enumeration set or any other complex data. In that case always use elements.
  • Elements are extensible while attributes are not so you'll need to take care about that if you are planing some changes in the future.
  • Sometimes its hard to tell what is meta-data and what is not.