Elements and Attributes
XML data can be represented as nested child elements or as attributes on a single element — both are valid, and choosing between them is a common design decision.
Elements vs Attributes
The same piece of information can often be represented either as a child element or as an attribute of its parent. Neither is universally 'correct' — the choice usually comes down to convention and whether the data is a core value or supplementary metadata.
<!-- Using elements -->
<student>
<id>1024</id>
<name>Ntokozo</name>
</student>
<!-- Using an attribute -->
<student id="1024">
<name>Ntokozo</name>
</student>
A Practical Guideline
A common convention: use attributes for metadata about an element (like an ID or a unit of measurement), and use child elements for the actual data content, especially anything that might need further structure or multiple values later.
Common Mistakes
- Overusing attributes for data that would be clearer and more extensible as child elements.
- Storing multiple values in a single attribute (like a comma-separated list) when multiple child elements would be more structured.
- Forgetting that an element can have any number of attributes, but each attribute name can only appear once per element.
- Assuming attributes support the same nested structure as elements — they can only hold simple text values.
Professional Tip
If a piece of data might need to hold multiple values, or might itself need further sub-structure someday, model it as a child element rather than an attribute — attributes can only ever be a single, simple text value.
Your Turn
Model a <product> element two different ways: once with price and currency as attributes, and once with price and currency as separate child elements. Consider which feels more natural.
Mini Quiz
What is a key limitation of XML attributes compared to child elements?