XML Syntax Rules
XML enforces a small set of strict syntax rules that every document must follow exactly, which is what allows any XML parser to reliably read any well-formed XML document.
The Core Rules
These rules are non-negotiable — a document that breaks even one of them is not valid XML and will be rejected by any conforming parser.
- Every document must have exactly one root element.
- Every opening tag must have a matching closing tag (or be self-closing).
- Tags must be properly nested — never overlapping.
- XML is case-sensitive: <Name> and <name> are different tags.
- Attribute values must always be quoted.
Correct Nesting
Elements must close in the reverse order they were opened — this is one of the most common mistakes when hand-writing XML.
<!-- Correct -->
<book><title>Learning XML</title></book>
<!-- Incorrect - overlapping tags -->
<book><title>Learning XML</book></title>
Common Mistakes
- Overlapping tags instead of properly nesting them, e.g. closing a parent element before its child.
- Forgetting that XML is case-sensitive, so <Book> and <book> are treated as entirely different elements.
- Leaving an attribute value unquoted, e.g. writing id=42 instead of id="42".
- Including more than one root element at the top level of a document.
Professional Tip
If you're ever unsure whether an XML document is correctly structured, run it through a validator or open it in a browser — most browsers will render well-formed XML as a collapsible tree and will show a clear parsing error if something is malformed.
Your Turn
Write a small XML document with intentionally overlapping tags, then correct the nesting so it becomes valid.
Mini Quiz
How many root elements can a valid XML document have?