Attributes
We were briefly introduced to the concept of element attributes in an earlier section, where an attribute is placed in the start tag of an element. An attribute describes a property of the element, along with a relevant value (generally in the context of an application.) If we observe carefully the logic behind organizing XML document elements as tree structures, we can see a duality between nested elements and element attributes.
For example, consider the monkey-business XML document of the previous topic, describing nested element structures. It can be reorganized to have fewer elements, overall (and thus, a less-deeper rooted tree) to look something like this:
<monkey-business venture-name="Simian Platform" />
<monkey-role title="Production Damager" name="KingKong" responsibility="Stop-erations" subordinates="Jerks" />
<monkey-role title="Deceptionist" name="Dunston" responsibility="Curt-essy" />
</monkey-business>
Of course, the smart reader will easily understand that the same information can be reorganized in several different ways by choosing various combinations of element nesting and attribute identification. The choice is up to the document author what he wants to put where, but there is also a method to the madness, as we shall see below.
One obvious difference between the 2 styles is that using attributes reduces the clutter in the XML document, with far lesser elements and much less nesting involved. The element "monkey-role" has no nested elements in the second example, whereas it had 3 to 4 elements nested inside in the first one. Because of this space conservation benefit, time efficiency and readability are achieved almost every time in all scenarios, why have nested elements at all? After all, isn't it excellence that we are always after?
The choice should, however, be context-specific. Although nesting elements has the above disadvantages, it is in fact preferable in several contexts. Since attributes are embedded within the start tags as properties, in several contexts they cannot be extracted with ease by an application. But the most important determinant is that sometimes, within an outer element, we want to have multiple elements of the same category, such as <monkey-role> in our example. If such an element was never unique, then we cannot use it effectively as an attribute of <monkey-business>! So it clearly depends on what the application's behavior will be, and how to model that behavior in the information.
Just as there are no pre-defined limits on the number of nested elements inside a containing element, there are none on the number of attribute-value pairs in an XML element. Only limits on the system govern these extreme bounds.