XML Syntax
XML enforces a small, strict set of syntax rules that keep every document parseable no matter which program reads it.
Why Strict Syntax Matters
HTML browsers are famously forgiving — they'll often render a page even with mismatched tags or missing quotes. XML parsers are not forgiving at all. A document that breaks any syntax rule isn't merely sloppy, it's invalid XML, and a compliant parser is required to refuse it. This strictness is deliberate: it guarantees that any XML parser, on any platform, interprets a document exactly the same way.
Every Element Needs a Closing Tag
In HTML, an element can sometimes be left open and the browser will still guess what you meant. In XML, every opening tag must have a matching closing tag, with no exceptions.
Closing Tags Are Required
<!DOCTYPE html>
<html>
<body>
<pre>
<!-- Wrong -->
<message>Hello world
<!-- Correct -->
<message>Hello world</message>
</pre>
</body>
</html>XML Is Case Sensitive
The tags <Message> and <message> are treated as two completely different elements. An opening tag and its closing tag must match in case exactly, or the document is invalid.
Matching Case Exactly
<!DOCTYPE html>
<html>
<body>
<pre>
<!-- Wrong: opening and closing tags differ in case -->
<Message>Hello</message>
<!-- Correct -->
<Message>Hello</Message>
</pre>
</body>
</html>Quoting Attributes and Proper Nesting
Attribute values must always be wrapped in quotation marks — single or double, used consistently — and never left bare. Elements must also be properly nested, meaning a child element has to close before its parent does, the same way nested parentheses have to close in reverse order of how they opened.
Quoting and Nesting Correctly
<!DOCTYPE html>
<html>
<body>
<pre>
<!-- Wrong: unquoted attribute and a child that outlives its parent -->
<book category=fiction><title>XML Basics</book></title>
<!-- Correct -->
<book category="fiction"><title>XML Basics</title></book>
</pre>
</body>
</html>- Every element needs a matching closing tag.
- Tags are case sensitive — <Item> and <item> are different elements.
- Elements must be properly nested — a child must close before its parent does.
- Attribute values must always be quoted.
- A document must have exactly one root element.
- Whitespace inside text content is preserved, unlike in HTML.
One Root Element
A valid XML document must have exactly one top-level element containing everything else. If two elements sit side by side at the very top with nothing wrapping them, the document is invalid — wrap them in a single shared root.
Exercise: XML Syntax
How does XML handle tag name casing compared to HTML?