XML Notes

Table of Contents

Section 6: Use of Elements vs. Attributes

Using an Attribute for sex:

<person sex="female">
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>

Using an Element for sex:

<person>
  <sex>female</sex>
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>

In the first example, sex is an attribute. In the last example, sex is an element. Both examples provide the same information to the reader. There are no fixed rules about when to use attributes to describe data, and when to use elements. My experience is, however; that attributes are handy in HTML, but in XML you should try to avoid them, as long as the same information can be expressed using elements. I tend to use attributes to contain id numbers and other elements that are not displayed to the user. For example:

<news id="84">
  <date>01/01/2004</date>
  <time>5:24 pm</time>
  <subject>I like Butter</subject>
  <article>Bork, bork, bork!</article>
</news>

Note that the use of the id as an attribute is simply my own preference, not a requirement of XML.

Here is another example, demonstrating how elements can be used instead of attributes. The following three XML documents contain exactly the same information. A date attribute is used in the first, a date element is used in the second, and an expanded date element is used in the third:

<?xml version="1.0"?>
<note date="12/11/02">
  <to>John</to>
  <from>Peter</from>
  <heading>Reminder</heading>
  <body>Don't forget to send me the data</body>
</note>

<?xml version="1.0"?>
<note>
  <date>12/11/02</date>
  <to>John</to>
  <from>Peter</from>
  <heading>Reminder</heading>
  <body>Don't forget to send me the data</body>
</note>

<?xml version="1.0"?>
<note>
  <date>
    <day>12</day>
    <month>11</month>
    <year>02</year>
  </date>
  <to>John</to>
  <from>Peter</from>
  <heading>Reminder</heading>
  <body>Don't forget to send me the data</body>
</note>

These are some of the problems using attributes:

  • Attributes can not contain multiple values (Elements can).

  • Attributes are not expandable (For future changes).

  • Attributes can not describe structures (Like child elements can).

  • Attributes are more difficult to manipulate through program code.

  • Attribute values are not easy to test against a DTD.

If you start using attributes as containers for XML data, you might end up with documents that are both difficult to maintain and manipulate. Therefore, you should use elements to describe your data. Use attributes only to provide information that is not relevant to the reader. The following example is what I would strongly advise against doing:

<?xml version=”1.0”?>
<note day=”12” month=”11” year=”02” to=”John” from=”Peter” heading=”Reminder” body=”Don’t forget to send me the data”/>