To E or Not To E: Elements vs. Attributes
April 12, 1999
You may have noticed in the Collection Markup Language example a
few seeming inconsistencies such as:
<Published publisher="Harmony Books">1992</Published>
compared with
<Chart>
<Peak>1</Peak> <!-- US implied -->
<Peak country="UK">2</Peak>
</Chart>
for the Book and CD parent elements,
respectively. Why didn't I make a Publisher
element, or why didn't I make peakUS and
peakUK attributes, instead of children elements of
Chart? Would these have worked?
<Publication>
<Published>1992</Published>
<Publisher>Harmony Book</Publisher>
</Publication>
and
<Chart peakUS="1" peakUK="2" />
Believe it or not, while not visually equivalent, they are
considered lexically equivalent. Either form would work just
fine.
But which is better? Is it best to make almost everything
elements, with attributes only used for details? Or is it
better to create fewer elements and use attributes liberally?
Ah, that is the $64,000 question! In fact, this question has
been kicking around the
SGML
community since at least 1992. The consensus is that there is
no one answer that applies to all situations. The decision
depends on what you intend to do with the markup. Generally
speaking, if my intention with Collection ML is to treat publisher
as a relatively unimportant detail (not to be accessed often),
whereas if I consider peak chart positions for any country
listed to be something I'll want to access frequently, then my
original definitions are appropriate. Some of the major
differences between elements and attributes are:
- order of attributes cannot be controlled (element order can be specified in a content model)
- attributes cannot be hierarchical
- attributes are more like metadata than content
- attributes are also useful for enumerated values (name token groups)
For details, examples, and many other opinions, see Robin Cover's
page on this subject,
SGML/XML: Using Elements and Attributes.
There is also a useful set of
guidelines by G. Ken Holman
posted to the newsgroup
comp.xml.text in early 1999.
Writing Our Own ML without a Net: Examples
Doing It With XML, Part 1
Viewing It With IE5, Take 1
|