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:
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:
Don't forget me this weekend!
This example uses a "date" element:
Don't forget me this weekend!
This example uses an expanded "date" element: (this is my favorite way):
Don't forget me this weekend!
Avoid using attributes?
Should you avoid using attributes?
Some attributes have the following problems:
- Attributes cannot contain multiple values (child elements can)
- Attributes are not easy to extend (for future requirement changes)
- Attributes cannot describe structure (child elements can)
- Attributes are harder to manipulate with program code
- Attribute values are not easy to test against a DTD
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!"> 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: Don't forget me this weekend! 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.
An exception to the attribute rule