XML Basics (part 1) - To Attribute Or Not To Attribute... (
Page 9 of 9 )
Elements can also contain
attributes, which provide additional information about the element. Attributes
are name-value pairs which appear within the start tag of an element and can be
used to provide additional descriptive parameters or default values to the element.
For example, the following XML snippet uses the attribute "sex" to provide additional
data on the <person> element:
<cast>
<person sex="male">Hugh Jackman</person>
<person sex="male">Patrick
Stewart</person>
<person sex="male">Ian McKellen</person>
<person
sex="female">Famke Janssen</person>
</cast>
Attributes must always appear after the element name, and attribute names are
case-sensitive. Attribute values must always be enclosed within quotation marks,
and the same attribute should not be repeated twice within the same element. If
your document is linked to a DTD, you can enforce rules on the types of values
an attribute may and may not accept.
It should be noted that the line between attributes and elements is often very
fine, since the two perform similar functions. For example, while it is perfectly
valid for me to describe a
<person sex="male">Hugh Jackman</person>
I could achieve exactly the same effect by breaking the data down and assigning
it to a series of elements.
<person>
<name>Hugh Jackman</name>
<sex>male</sex>
</person>
In other words - the decision as to whether to use an attribute or an element
can sometimes be a tricky one, and needs to be made on a case-by-case basis. Most
experts seem to agree that this is an implementation decision, and must be made
keeping in mind the purpose for which the document is going to be used.
Valid reasons for using attributes over elements would include assigning an ID
to a specific element,
<review id="6548450">...</review>
or describing characteristics of the element itself.
The <animal color="red">wolf</animal> jumped over the <vegetable
color="blue">aubergine</vegetable>
If you need to restrict attribute values to some pre-defined options, you can
use a DTD to specify a list of allowed and default values, thereby cutting down
on the possibility of errors and incompatible data.
If you're interested in a detailed discussion and debate of this issue, you should
make it a point to visit
http://xml.coverpages.org/elementsAndAttrs.html, which has some interesting comments and opinions by experts in the field on
this very topics.
That's about it for the moment. In the next article, I'm going to continue this
discussion of basic XML concepts with a look at entities, namespaces, and processing
instructions - so make sure that you don't miss that one. Until then...stay healthy!
This article copyright Melonfire 2001. All rights reserved.