XML Elements

XML elements are the building blocks of every document, and a handful of naming and nesting rules keep them predictable.

What Is an Element?

An XML element is everything from an opening tag to its matching closing tag, including whatever it contains: text, attributes, or other elements. <author>George Orwell</author> is a complete element — an opening tag, some text content, and a closing tag.

Element Naming Rules

XML gives you freedom to name elements however you like, but that freedom comes with a few restrictions every parser enforces.

  • Names can contain letters, digits, hyphens, underscores, and periods.
  • A name must start with a letter or an underscore, never a digit or punctuation.
  • Names cannot contain spaces.
  • Names cannot start with the letters xml, in any casing such as XML or Xml — that prefix is reserved.
  • Names are case sensitive, so <Price> and <price> are different elements.

Valid and Invalid Names

<!DOCTYPE html>
<html>
<body>

<pre>
&lt;!-- Valid --&gt;
&lt;first-name&gt;John&lt;/first-name&gt;
&lt;_id&gt;102&lt;/_id&gt;

&lt;!-- Invalid --&gt;
&lt;1st-name&gt;John&lt;/1st-name&gt;
&lt;first name&gt;John&lt;/first name&gt;
</pre>

</body>
</html>

Nesting Elements

Elements can contain other elements, letting you represent structured records rather than a single flat value. A <person> element, for instance, can hold separate <first-name> and <last-name> children instead of one combined name field.

Nested Elements

<!DOCTYPE html>
<html>
<body>

<pre>
&lt;person&gt;
  &lt;first-name&gt;John&lt;/first-name&gt;
  &lt;last-name&gt;Smith&lt;/last-name&gt;
  &lt;address&gt;
    &lt;city&gt;New York&lt;/city&gt;
    &lt;zip&gt;10001&lt;/zip&gt;
  &lt;/address&gt;
&lt;/person&gt;
</pre>

</body>
</html>

Empty Elements

An element with no content is called an empty element. It can be written as a pair of tags with nothing between them, or collapsed into a single self-closing tag ending in />. Both forms mean exactly the same thing.

Two Ways to Write an Empty Element

<!DOCTYPE html>
<html>
<body>

<pre>
&lt;!-- Written as a pair --&gt;
&lt;contact-verified&gt;&lt;/contact-verified&gt;

&lt;!-- Self-closing shorthand --&gt;
&lt;contact-verified /&gt;
</pre>

</body>
</html>
Note: Empty elements are common when the useful information lives entirely in attributes, or when an element's mere presence signals something, such as a <deleted /> flag with nothing further to say.
Note: Element names are case sensitive, and this trips up beginners constantly. <Book> and <book> are treated as two unrelated elements by any XML parser, even though they look almost identical.
RuleExample that follows itExample that breaks it
Must start with a letter or underscore<_note><1note>
No spaces allowed<full-name><full name>
Cannot start with 'xml'<data><xmldata>
Case sensitive<Title> is not <title>mixing the two by accident

Exercise: XML Elements

Which is a valid rule for naming XML elements?