XML Attributes
XML elements can have attributes, similar to HTML.
Attributes provide extra information about an element.
XML Attributes
In HTML, attributes provide extra information about elements:
Attributes usually provide information that is not part of the data. In the example below, the file type is unrelated to the data, but it is important to the software that needs to process the element:
XML Attributes Must Be Quoted
Attribute values must be enclosed in quotes, but either single or double quotes can be used. For example, a person's gender can be written in the person element like this:
Or like this:
If an attribute value itself contains double quotes, you can use single quotes, as in this example:
Or you can use character entities:
XML elements vs. attributes
Look at 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 hard rules about when to use attributes and when to use elements. My experience is that in HTML, attributes are convenient to use, but in XML you should try to avoid using attributes. If the information feels like data, use an element.
My Favorite Approach
The following three XML documents contain exactly the same information:
The first example uses a date attribute:
The second example uses a date element:
The third example uses an extended date element (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 expandable (for future changes)
Attributes are difficult to read and maintain. Try to use elements to describe data, and use attributes only to provide information that is not part of the data.
Don't do silly things like this (this is not how XML should be used):
to="Tove" from="Jani" heading="Reminder" body="Don't forget me this weekend!"> Sometimes ID references are assigned to elements. These ID indexes can be used to identify XML elements, working in the same way as the id attribute in HTML. This example demonstrates this: The id attribute above is merely an identifier used to distinguish different notes. It is not part of the note's data. The idea we strongly want to convey here is: metadata (data about data) should be stored as attributes, while the data itself should be stored as elements.
XML Attributes for Metadata