TUTORIAL HOME
XML Attributes
❮ Previous Next ❯
XML elements can have attributes, just like HTML.
Attributes are designed to contain data related to a specific element.
XML Attributes Must be Quoted
Attribute values must always be quoted. Either single or double quotes can be used.
For a person’s gender, the 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
Take a look at these examples:
Anna
Smith
female
Anna
Smith
In the first example gender is an attribute. In the last, gender is an element. Both examples provide the same information.
There are no rules about when to use attributes or when to use elements in XML.
My Favorite Way
The following three XML documents contain exactly the same information:
A date attribute is used in the first example:
Tove
Jani
A element is used in the second example:
2008-01-10
Tove
Jani
An expanded element is used in the third example: (THIS IS MY FAVORITE):
2008
01
10
Tove
Jani
Avoid XML Attributes?
Some things to consider when using attributes are:
attributes cannot contain multiple values (elements can)
attributes cannot contain tree structures (elements can)
attributes are not easily expandable (for future changes)
Don’t end up like this:
<note day="10" month="01" year="2008"
to=”Tove” from=”Jani” heading=”Reminder”
body=”Don’t forget me this weekend!”>
XML Attributes for Metadata
Sometimes ID references are assigned to elements. These IDs can be used to identify XML elements in much the same way as the id attribute in HTML. This example demonstrates this:
Tove
Jani
Reminder
Don’t forget me this weekend!
Jani
Tove
Re: Reminder
I will not
The id attributes above are for identifying the different notes. It is not a part of the note itself.
What I’m trying to say here is that metadata (data about data) should be stored as attributes, and the data itself should be stored as elements.
❮ Previous Next ❯
