Dtd El_Vs Attr
## XML Elements vs. Attributes
* * *
In XML, there is no strict rule on when to use attributes and when to use child elements.
* * *
## Using Elements vs. Attributes
Data can be stored either in child elements or attributes.
Let's look at these examples:
Anna
Smith
female
Anna
Smith
In the first example, "sex" is an attribute. In the second example, "sex" is a child element. However, both provide the same information.
There is no specific rule dictating when to use attributes versus child elements. My experience is that in HTML we tend to use attributes more often, but in XML, using child elements feels more natural for data representation.
* * *
## My Preferred Approach
**I prefer storing data in child elements**
The following three XML documents contain exactly the same information:
This example uses the "date" attribute:
Tove
Jani
Reminder
Don't forget me this weekend!
This example uses the "date" element:
12/11/2002
Tove
Jani
Reminder
Don't forget me this weekend!
This example uses an extended "date" element: (this is my favorite approach):
12
11
2002
Tove
Jani
Reminder
Don't forget me this weekend!
* * *
## Should You Avoid Attributes?
Should you avoid using attributes?
Some issues with attributes include:
* Attributes cannot contain multiple values (child elements can)
* Attributes are not easily extensible (for future changes)
* Attributes cannot describe structure (child elements can)
* Attributes are harder to manipulate via program code
* Attribute values are difficult to test against DTD
If you use attributes as data containers, the final XML document will become hard to read and maintain. Try using **elements** to represent your data. Only use attributes when the provided data is unrelated or non-essential.
Do not do this (this is not how XML should be used):
* * *
## An Exception to the Attribute Rule
Rules always have exceptions
I have one exception to the rule about attributes.
Sometimes I assign IDs to elements. These IDs can be accessed similarly to NAME or ID attributes in HTML. The following example illustrates this approach:
Tove
Jani
Reminder
Don't forget me this weekend!
Jani
Tove
Re: Reminder
I will not!
In the above XML file, the ID serves merely as a counter or unique identifier to distinguish different notes, rather than being part of the actual data.
What I want to emphasize here is that metadata (data about data) should be stored as attributes, while the actual data should be stored as elements.
YouTip