When to use attributes and when to use elements in XML

So I was wondering today if there is a ruling on when to use attributes in XML. It seems to me it is much easier to parse out data if there are no attributes, but on the other hand I don’t want to put data that isn’t pertinent to the information being held. So my first option was this:

<location>
	<id>11</id>
	<name>Downtown</name>
	<address>225 Main Street Nowheresville</address>
</location>

My second option was this:

<location id="11">
	<name>Downtown</name>
	<address>225 Main Street Nowheresville</address>
</location>

I did some research and found that everyone and their mother was saying, data goes in elements, metadata in attributes. So I did some more research just to make sure I was understanding it completely. I found these two tips to be clearer.

  1. If the information is pertainant to the whole information as a whole, then it is best to make it an element.
  2. Conversely, if the information is used as a reference for other aspects of an application or web site, it is best to set it as an attribute.

Quite possibly the best tips I found were from the X12 Reference Model For XML Design.

  1. “Attributes are atomic and cannot be extended and its existence should serve to remove any and all possible ambiguity of the element it describes. They are ‘adjectives’ to the element ‘noun’.”
  2. “Use elements for data that will be produced or consumed by a business application, and attributes for metadata.”

Further reading: Principles of XML design: When to use elements versus attributes
Elements vs. attributes

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>