Attributes provide the solution for adding richer metadata to elements. An attribute consists of an attribute name and an attribute value . The attribute value is bounded by quotation marks. This attribute specification appears in the start tag of the element, and you can specify as many attributes for an element as you consider necessary. As with all XML constructs, attribute names and attribute values are case sensitive. As a stylistic convention, some authors use upper camel case text for element names and lower camel case text for attribute names so that they can easily distinguish between names of elements and names of attributes. Example 2-5 shows how adding attributes to the contact database could make it possible to use the database. Example 2-5<Database dbType="Oracle" address="192.168.1.1"> <Table name="Person"> <Column dataType="String">Name</Column> <Column dataType ="String">Phone Number</Column> </Table> <Table name="Conversation"> <Column dataType ="Date">Date</Column> <Column dataType ="String">Person</Column> </Table> </Database> Figure 2-4 shows the element tree of this document. Note that it is exactly the same as the tree in Figure 2-3. From Example 2-4 to Example 2-5, the element hierarchy did not change. Even the element content did not change. What did attributes add? They added further metadata. They added information that will allow consumers of the document ”in this case database access programs ”to use the content effectively. Figure 2-4. Contact Database Element Tree with Attributes
In most cases, attributes aren't strictly necessary. You could put the same information into a subelement, but often it seems more convenient and cleaner to use attributes for small pieces of contextual information rather than subelements. Each attribute in Example 2-5 provides the context necessary to interpret the element content. The "dbType" attribute tells it what database networking protocol to use. The "location" attribute tells it where to find the database. The "name" attribute tells it how to select the appropriate table. The "dataType" attributes tell it how to form valid queries for each column. Obviously, a real version of this application might require even more attributes, but with XML, you could easily provide them. |