XML Attributes
XML elements have attributes, similar to HTML.
Attributes provide additional information about elements.
XML Attributes
In HTML, attributes provide additional information about elements:
Attributes usually provide information that is not part of the data. In the following example, the file type is not part of the data, but it is important for software that needs to process this element:
XML Attributes Must Be Quoted
Attribute values must be enclosed in quotes, either single or double quotes can be used. For example, a person's gender, the person element can be written like this:
Or like this:
If the attribute value itself contains double quotes, you can use single quotes, like in this example:
Or you can use character entities:
XML Elements vs. Attributes
Consider these examples:
In the first example, sex is an attribute. In the second example, sex is an element. Both examples provide the same information.
There are no rules that tell us when to use attributes and when to use elements. My experience is that in HTML, attributes are very convenient, but in XML, you should avoid using attributes. If the information feels like data, then use elements.
My Favorite Way
The following three XML documents contain exactly the same information:
In the first example, the date attribute is used:
In the second example, the date element is used:
In the third example, an extended date element is used (this is my favorite):
Avoid XML Attributes?
Some problems caused by using attributes:
Attributes cannot contain multiple values (elements can)
Attributes cannot contain tree structures (elements can)
Attributes are not easily extensible (for future changes)
Attributes are difficult to read and maintain. Use elements to describe data and only use attributes to provide information that is not part of the data.
Do not do something like this (this is not how XML should be used):
XML Attributes for Metadata
Sometimes ID references are assigned to elements. These ID indexes can be used to identify XML elements, similar to how the id attribute works in HTML. This example demonstrates this:
The id attribute above is just an identifier to identify different labels. It is not part of the label data.
The idea we strongly convey here is that metadata (data about data) should be stored as attributes, and the data itself should be stored as elements.