Elements & Attributes

An XML document is really just elements nested inside each other, and each element can optionally carry attributes — extra pieces of information written inside its opening tag.

Elements: the building blocks

An element is an opening tag, some content, and a matching closing tag. That content can be plain text, other elements, or a mix of both:

XML book.xml
<book>
  <title>Dune</title>
  <author>Frank Herbert</author>
  <year>1965</year>
</book>

<book> is the parent element here, and <title>, <author>, and <year> are its children — each one a complete element in its own right, just nested one level deeper.

Attributes: extra information on the tag itself

An attribute is a name="value" pair written inside an opening tag, rather than as separate content between tags:

XML book.xml
<book id="42" language="en">
  <title>Dune</title>
</book>

Here id and language are attributes of <book>. An element can have any number of attributes, separated by whitespace, and — unlike element order, which XML does preserve — attribute order carries no meaning at all.

Attribute or child element?

XML gives you no strict rule for when to use an attribute versus a nested element — both examples above are valid XML describing the same book. In practice, most people follow a loose convention: attributes for short, simple, single-value metadata about an element (an ID, a language code, a flag), and child elements for anything that's part of the actual data — especially anything that might itself need structure, repeat multiple times, or contain other elements.

XML a case where a child element wins
<book id="42">
  <title>Dune</title>
  <genre>Science Fiction</genre>
  <genre>Adventure</genre>
</book>

A book can belong to multiple genres, so <genre> repeats as a child element — an attribute can only hold one value per name, so genre="Science Fiction, Adventure" would force you to invent your own comma-splitting convention instead of letting the XML structure itself carry that information.

Note: an attribute name can only appear once per element — <book id="1" id="2"> is not well-formed XML, and a parser will reject it outright rather than just keeping the last one, which is how some other loosely-specified formats might handle a duplicate key.