There's one essential piece of XML markup that we haven't discussed yet: attributes. An attribute is an XML syntactic structure that allows authors to include additional information about an element in a name/value pair. If you are familiar with HTML, you have already used attributes in an <a>
tag, like the following example:
<a href="index.html">Go to the home page</a>
In this case, the href attribute contains the name of the file that is the target of the link.
There are a few things to remember when working with attributes:
- The attribute's name must be separated from the attribute value by an equals (=) sign.
- The attribute value must be surrounded by quotes - you can use either single or double quotes.
- Attributes only need to be included in the opening tag for an element.
Attributes are sometimes thought of as the adjectives of the XML language. They provide a way to include some additional information about a given element. Although attributes may seem simple on the surface, the decision to use attributes versus using child elements is not quite as straightforward.
For example, consider the <begin-date>
element that we created earlier. We could have included it as an attribute of the <job> element, as shown in the following example:
<job start="1/20/2010">
In fact, many XML authors might do that. Neither is definitely right or wrong. There is only one absolute certainty when deciding: if you'll have multiple instances of that type of data. Each element can have only one attribute of the same name. However, an element can have multiple child elements of the same name. If you will need to markup multiple similar pieces of information, use elements.
There are several factors that could affect the decision to use attributes or child elements. You'll want to think about the following before deciding to include information as an attribute or a child element:
- How essential is the information? If it is truly essential, consider using a child element. If it is incidental, consider using an attribute.
- Does the information need to be displayed to the user? If so, you may want to use child elements. It is less convenient to pull the value of an attribute from an element using processing languages such as XSLT.
- How much information will be included in the attribute? Attributes can become difficult to read after a few words.
There are two places where attributes might be useful in our document. First, we could add an attribute to <midwest-job-listing>
that indicates the date the document was last updated. We could also move the job ID, currently part of the data included in <title>
, to an attribute that's part of <job>
. Since the job's ID is something that users of the HR website might not necessarily be concerned with, it might be a good idea to include it as an attribute so it's still visible to people who may edit job_postings.xml after we've created it.
Let's go ahead and add attributes to <midwest-job-listing>
and <job>
.