XML Attributes
Attributes attach extra facts about an element directly to its opening tag, as an alternative to nesting that data as a child element.
What Is an Attribute?
An attribute is a name/value pair written inside an element's opening tag, giving extra information about that element without adding a separate child. In <book category="fiction">, category is an attribute of <book>.
An Attribute in Action
<!DOCTYPE html>
<html>
<body>
<pre>
<book category="fiction">
<title>Harry Potter</title>
<author>J K. Rowling</author>
</book>
</pre>
</body>
</html>The Same Data as a Child Element
Anything an attribute can express, a child element can express too — it's purely a design choice, not a technical requirement. The example above could just as validly be written with category as its own nested element instead of an attribute.
The Same Fact as a Child Element
<!DOCTYPE html>
<html>
<body>
<pre>
<book>
<category>fiction</category>
<title>Harry Potter</title>
<author>J K. Rowling</author>
</book>
</pre>
</body>
</html>When to Prefer Attributes
There's no rule enforced by XML itself, but experienced authors follow a few conventions. Attributes work well for metadata about an element — an id, a unit, a date stamp, a language code — while the element's own content, and anything structured or repeatable, is usually better as a child element.
- Use attributes for metadata that describes the element, not the core data itself, like an id or a unit.
- Use child elements when the value might need to hold multiple pieces of data or repeat.
- Attribute values cannot contain their own nested structure; child elements can.
- An attribute name can only appear once per element, so an element can't have two id attributes.
- Child elements are generally easier to extend later without breaking existing consumers of the data.
Attributes vs. Nested Structure
<!DOCTYPE html>
<html>
<body>
<pre>
<!-- Works fine: a single simple value as an attribute -->
<temperature unit="celsius">22</temperature>
<!-- Would NOT work well as an attribute: multiple related values -->
<address>
<street>221B Baker Street</street>
<city>London</city>
</address>
</pre>
</body>
</html>Exercise: XML Attributes
What must every XML attribute value have?