XML allows you to attach additional information to elements by including attributes in the elements’ start tags. Attributes are name/value pairs. The following book element expresses year as an attribute rather than as a child element: |
<book year=”2003”> |
<title>XSLT Programmers Reference</title> <author>Michael Kay</author> |
</book> |
Attribute values must be enclosed in single or double quotation marks and may include spaces and embedded quotation marks. (An attribute value delimited by single quotation marks can contain double quotation marks and vice versa.) Attribute names are subject to the same restrictions as element names and therefore can’t include spaces. The number of attributes an element can be decorated with is not limited. |
When defining a document’s structure, it’s sometimes unclear —especially to XML newcomers— whether a given item should be defined as an attribute or an element. In general, attributes should be used to define out-of-band data and elements to define data that is integral to the document. In the previous example, it probably makes sense to define year as an element rather than an attribute because year provides important information about the book in question. |