Attribute vs. Element?
Home ] Up ] The Document Prolog ] XML Elements ] The Root Element ] XML Attributes ] [ Attribute vs. Element? ] Whitespace and Comments ] XML Character Entities ] CDATA Sections ] Processing Instructions ] Well-Formed Documents ]

 

 

So, how do we choose whether to use an element or an attribute?

A simple rule is:

  • If an item of data names something (i.e. is a noun), then it most likely should be an element
  • If an item of data modifies something (i.e. is an adjective), then most likely it should be an attribute.

In general, you should try to make attributes be atomic -- that is, indivisible.  If you can subdivide an item into pieces, then you should use elements. For example:

<?xml version="1.0" encoding="utf-8"?>
<address>
  <street>31 Concord Rd.</street>
  <city>Lower Farthing</city>
  <state>Old Hampshire</state>
  <zip>99999</zip>
</address>

One possible exception to this is when a compound value could be considered to be a data type.  For example, dates are typically considered to be members of a particular data type, and so may be modeled as attributes.

Clearly, if a data item is multi-valued, then it must be modeled using an element.

 
The page was last updated February 19, 2008