Attributes are simple name/value pairs associated with an element.
They are attached to the start-tag, as shown below, but not to the end-tag:
<name nickname='Shiny John'> <first>John</first> <middle>Fitzgerald Johansen</middle> <last>Doe</last> </name>
Attributes must have values – even if that value is just an empty string (like “”) – and those values must be in quotes. So the following, which is part of a common HTML tag, is not legal in XML:
and neither is this:
Either single quotes or double quotes are fine, but they have to match. For example, to make this well-formed XML, you can use one of these:
<input checked='true'> <input checked="true">
but you can’t use:
Because either single or double quotes are allowed, it’s easy to include quote characters in your attribute values, like “John’s nickname” or ‘I said “hi” to him’. You just have to be careful not to accidentally close your attribute, like ‘John’s nickname’; if an XML parser sees an attribute value like this, it will think you’re closing the value at the second single quote, and will raise an error when it sees the “s” which comes right after it.
The same rules apply to naming attributes as apply to naming elements: names are case sensitive, can’t start with “xml”, and so on. Also, you can’t have more than one attribute with the same name on an element. So if we create an XML document like this:
<bad att="1" att="2"></bad>
we will get the following error in IE5:
Try It Out – Adding Attributes to Al’s CD
With all of the information we recorded about our CD in our earlier Try It Out, we forgot to include the CD’s serial number, or the length of the disc. Let’s add some attributes, so that our hypothetical CD Player application can easily find this information out.
1. Open your cd.xml file created earlier, and resave it to your hard drive as cd2.xml.
2. With our new-found attributes knowledge, add two attributes to the <CD> element, like this:
<CD serial=B6B41B disc-length='36:55'> <artist>"Weird Al" Yankovic</artist> <title>Dare to be Stupid</title> <genre>parody</genre> <date-released>1990</date-released> <song> <title>Like A Surgeon</title> <length> <minutes>3</minutes> <seconds>33</seconds> </length> <parody> <title>Like A Virgin</title> <artist>Madonna</artist> </parody> </song> <song> <title>Dare to be Stupid</title> <length> <minutes>3</minutes> <seconds>25</seconds> </length> <parody></parody> </song> </CD>
3. If you typed in exactly what’s written above, when you display it in IE5 it should look something like this:
4. Now edit the first attribute, like this:
<CD serial='B6B41B' disc-length='36:55'>
5. Re-save the file, and view it in IE5. It will look something like this: