Easy Tutorial
❮ Index Dtd Building ❯

XML Elements vs. Attributes


In XML, there is no specific rule on when to use attributes and when to use child elements.


Using Elements vs. Attributes

Data can be stored in child elements or attributes.

Let's look at these examples:

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

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


My Preferred Way

I prefer storing data in child elements

The following three XML documents contain exactly the same information:

This example uses the "date" attribute:

This example uses the "date" element:

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


Avoid Using Attributes?

Should you avoid using attributes?

Some attributes have the following issues:

If you use attributes as data containers, the resulting XML document will be difficult to read and maintain. Try using elements to describe data. We only recommend using attributes when the provided data is irrelevant information.

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


An Exception to the Attribute Rule

There is always an exception to the rule

There is one exception to the rule about attributes.

Sometimes I specify an ID applied to an element. These IDs can be accessed in many of the same situations in HTML as NAME or ID attributes to access XML elements. The following example shows this approach:

In the above example, the ID is just a counter, or a unique identifier, to identify different tags rather than being part of the data.

Here I want to say that metadata (data about data) should be stored as attributes, and the data itself should be stored as elements.

❮ Index Dtd Building ❯