XML Attributes

XML elements can have attributes in the start tag, just like HTML.

Attributes provide additional information about elements.


XML Attributes

From HTML you will remember this: . The "src" attribute provides additional information about the element.

In HTML (and in XML) attributes provide additional information about elements:


Attributes often provide information that is not a part of the data. In the example below, the file type is irrelevant to the data, but important to the software that wants to manipulate the element:

computer.gif


XML Attributes Must be Quoted

Attribute values must always be enclosed in quotes, but either single or double quotes can be used. For a person's sex, the person tag 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 sex is an attribute. In the last, sex is an element. Both examples provide the same information.

There are no rules about when to use attributes and when to use elements. Attributes are handy in HTML. In XML my advice is to avoid them. Use elements instead.


My Favorite Way

The following three XML documents contain exactly the same information:

A date attribute is used in the first example:


Tove
Jani
Reminder
Don't forget me this weekend!

A date element is used in the second example:


10/01/2008
Tove
Jani
Reminder
Don't forget me this weekend!

An expanded date element is used in the third: (THIS IS MY FAVORITE):



10
01
2008

Tove
Jani
Reminder
Don't forget me this weekend!


Avoid XML Attributes?

Some of the problems with 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)

Attributes are difficult to read and maintain. Use elements for data. Use attributes for information that is not relevant to the data.

Don't end up like this:

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 above is just an identifier, to identify 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 that data itself should be stored as elements.

Mix it