Attributes

Attributes in XML documents come in two flavors: data attributes and metadata attributes. Data attributes are used to provide the actual data for an element. For example, the following attributes (name and age) provide the data for the Pet element:

<Pet name='Shnuckums' age="4">Dog</Pet>

Notice that the age attribute is wrapped in quotes even though the value itself is a number. This is because unlike elements, attributes are textual. This means that attributes must be wrapped in either single or double quotes.

You may also see attributes that exist in an empty element that contains no nested children. In these situations, you will see the attributes formatted as such:

Metadata attributes provide descriptive information about the contents of elements. For instance, in the following example, the Customer element has an attribute called id that provides that Customer with a unique identifier:

<?xml version="1.0"?> <MyTable>

<Customer id="1"/> <Quarter>Q1</Quarter> <Region>North</Region> <Revenue>25000</Revenue>

Many new users of XML find the concept of attributes versus elements a bit confusing. After all, most elements can be easily converted to attributes (or vice versa) and the XML document would parse just fine. For example, the Customer id attribute could just as easily be presented in an element as such: <id>1</ id >. There are, however, general rules of thumb that most XML documents seem to adhere to when it comes to elements versus attributes:

□ If the content is not an actual data item, but a descriptor of the data (record number, index number, unique identifier, and so forth), then an attribute is typically used.

□ Elements are used for any content that consists of multiple values.

□ If there is a chance that the content will expand in structure to include children, then elements are typically used.

Was this article helpful?

0 0

Post a comment