XML Attributes vs. Elements


This post continues from the post on XML Trees and discusses the two different styles of writing XML documents. Generally you should choose elements over attributes, with the exception of metadata, as w3schools.com explains.

In the first example gender is an attribute. In the last, gender is an element. Both examples provide the same information. There are no rules about when to use attributes or when to use elements in XML.

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

There are no rules, but as a programmer you might appreciate the the third way in the following examples from w3schools.com is the best way. If you work with databases, or even spreadsheets, you will appreciate that having the first name and last name of a person stored in two separate columns is easier that having them stored in one column. It is easier to create a third column and concatenate the first and last name with a space in between than it is to separate the first and last name when they are in the same column. The following three documents have the same information, but the last example is the preferred way.

<note date="2008-01-10">
  <to>Tove</to>
  <from>Jani</from>
</note>
<note>
  <date>2008-01-10</date>
  <to>Tove</to>
  <from>Jani</from>
</note>

The best way:

<note>
  <date>
    <year>2008</year>
    <month>01</month>
    <day>10</day>
  </date>
  <to>Tove</to>
  <from>Jani</from>
</note>
Series Navigation<< XML Online EditorXML Tree >>

Leave a comment

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