XML attribute vs XML element XML attribute vs XML element xml xml

XML attribute vs XML element


I use this rule of thumb:

  1. An Attribute is something that is self-contained, i.e., a color, an ID, a name.
  2. An Element is something that does or could have attributes of its own or contain other elements.

So yours is close. I would have done something like:

EDIT: Updated the original example based on feedback below.

  <ITEM serialNumber="something">      <BARCODE encoding="Code39">something</BARCODE>      <LOCATION>XYX</LOCATION>      <TYPE modelNumber="something">         <VENDOR>YYZ</VENDOR>      </TYPE>   </ITEM>


Some of the problems with attributes are:

  • 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

If you use attributes as containers for data, you end up with documents that are difficult to read and maintain. Try to use elements to describe data. Use attributes only to provide information that is not relevant to the data.

Don't end up like this (this is not how XML should be used):

<note day="12" month="11" year="2002"       to="Tove" to2="John" from="Jani" heading="Reminder"        body="Don't forget me this weekend!"> </note>

Source: http://www.w3schools.com/xml/xml_dtd_el_vs_attr.asp


"XML" stands for "eXtensible Markup Language". A markup language implies that the data is text, marked up with metadata about structure or formatting.

XHTML is an example of XML used the way it was intended:

<p><span lang="es">El Jefe</span> insists that you    <em class="urgent">MUST</em> complete your project by Friday.</p>

Here, the distinction between elements and attributes is clear. Text elements are displayed in the browser, and attributes are instructions about how to display them (although there are a few tags that don't work that way).

Confusion arises when XML is used not as a markup language, but as a data serialization language, in which the distinction between "data" and "metadata" is more vague. So the choice between elements and attributes is more-or-less arbitrary except for things that can't be represented with attributes (see feenster's answer).