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>
<!-- Valid -->
<first-name>John</first-name>
<_id>102</_id>
<!-- Invalid -->
<1st-name>John</1st-name>
<first name>John</first name>
</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>
<person>
<first-name>John</first-name>
<last-name>Smith</last-name>
<address>
<city>New York</city>
<zip>10001</zip>
</address>
</person>
</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>
<!-- Written as a pair -->
<contact-verified></contact-verified>
<!-- Self-closing shorthand -->
<contact-verified />
</pre>
</body>
</html>Exercise: XML Elements
Which is a valid rule for naming XML elements?