Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

XML Elements vs. Attributes

XML elements vs. attributes


In XML there is no rule about when to use attributes and when to use child elements.


Using elements vs. attributes

Data can be stored in child elements or in attributes.

Let us look at these examples:

  Anna

  Smith

  female

  Anna

  Smith

In the first example "sex" is an attribute. In the later example, "sex" is a child element. But both provide the same information.

There is no particular rule about when to use attributes and when to use child elements. My experience is to use attributes more in HTML, but in XML using child elements feels more like data.


The way I like

I like to store data in child elements

The following three XML documents contain exactly the same information:

This example uses a "date" attribute:

  Tove

  Jani

  Reminder

  Don't forget me this weekend!

This example uses a "date" element:

  12/11/2002

  Tove

  Jani

  Reminder

  Don't forget me this weekend!

This example uses an expanded "date" element: (this is my favorite way):

 

    12

    11

    2002

 

  Tove

  Jani

  Reminder

  Don't forget me this weekend!


Avoid using attributes?

Should you avoid using attributes?

Some attributes have the following problems:

If you use attributes as data containers, the resulting XML document will be hard to read and maintain. Try usingElementto describe data. We recommend attributes only when the data provided is not part of the information.

Do not end up like this (this is not how XML should be used):

to="Tove" from="Jani" heading="Reminder"

body="Don't forget me this weekend!">


An exception to the attribute rule

Rules always have another

I have one exception to the rule about attributes.

Sometimes I assign IDs to elements. These ID references can be used in HTML in many of the same situations as NAME or ID attributes to access XML elements. The following example shows this approach:

  Tove

  Jani

  Reminder

  Don't forget me this weekend!

  Jani

  Tove

  Re: Reminder

  I will not!

In the XML file of the example above, the ID is merely a counter or a unique identifier for distinguishing different notes, not part of the data.

The point I want to make here is that metadata (data about data) should be stored as attributes, while the data itself should be stored as elements.