XML Attributes
XML elements can have attributes,
just like HTML.
Attributes provide additional
information about an element.
XML
Attributes
In HTML, attributes provide additional
information about elements:
<img src="screen.gif">
<a href="example.asp">
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 can be important to the software that wants to
manipulate the element:
<file type="gif">screen.gif</file>
XML
Attributes Must be Quoted
Attribute values must always be quoted.
Either single or double quotes can be used. For a person's sex, the person
element can be written like this:
<person sex="female">
or like this:
<person sex='female'>
If the attribute value itself contains
double quotes you can use single quotes, like in this example:
<gangster name='Adam "Shotgun" Zuckenberg'>
or you can use character entities:
<gangster name="Adam "Shotgun" Zuckenberg">
XML
Elements vs. Attributes
Take a look at these examples:
<person sex="female">
<firstname>Angelina</firstname>
<lastname>Will Smith</lastname>
</person>
<person>
<sex>female</sex>
<firstname>Angelina</firstname>
<lastname>Will Smith</lastname>
</person>
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 or when to use elements. Attributes are handy in HTML.
In XML my
advice is to avoid them.
Use elements instead.
Best
Way Practised
The following three XML documents
contain exactly the same information:
A date attribute is used in the first
example:
<note date="10/01/2008">
<to>Tom</to>
<from>Jerry</from>
<heading>Reminder</heading>
<body>Don't forget Birthday Party this weekend!</body>
</note>
A date element is used in the second
example:
<note>
<date>10/01/2008</date>
<to>Tom</to>
<from>Jerry</from>
<heading>Reminder</heading>
<body>Don't forget Birthday Party this weekend!</body>
</note>
An expanded date element is used in the
third: (THIS IS MY FAVORITE):
<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>Tom</to>
<from>Jerry</from>
<heading>Reminder</heading>
<body>Don't forget Birthday Party this weekend!</body>
</note>