Getting Started Lesson 2 of 9
XML Syntax Rules — Well-Formed Documents
The rules every XML document must follow — the XML declaration, one root element, closing every tag, proper nesting, case sensitivity, quoted attributes, entities and comments.
XML is strict. A document that follows all the syntax rules is called well-formed. If even one rule is broken, XML programs refuse to read the document at all, unlike HTML, where browsers quietly fix mistakes.
The XML declaration
<?xml version="1.0" encoding="UTF-8"?>
This optional first line says the XML version and the character encoding. If you include it, it must be the very first thing in the file, with nothing before it, not even a space.
Rule 1: exactly one root element
<!-- Wrong: two top-level elements -->
<student>Ana</student>
<student>Ben</student>
<!-- Right: one root wraps everything -->
<students>
<student>Ana</student>
<student>Ben</student>
</students>
Rule 2: every element must be closed
<name>Ana</name> <!-- closing tag -->
<photo/> <!-- self-closing empty element -->
HTML lets you write <br> without closing it; XML doesn't.
Rule 3: proper nesting
<!-- Wrong -->
<b><i>Mabuhay</b></i>
<!-- Right -->
<b><i>Mabuhay</i></b>
The last element opened must be the first one closed, like stacked plates.
Rule 4: tags are case-sensitive
<Name>Ana</name> is an error: the opening and closing tags must match exactly.
Rule 5: attribute values must be quoted
<student lrn="136728140001" grade='10'>Ana</student>
Single or double quotes are fine, but they're required.
Rule 6: special characters need entities
< and & can't appear directly in text, because they start tags and entities. Use these five predefined entities:
| Character | Entity |
|---|---|
| < | < |
| > | > |
| & | & |
| " | " |
| ' | ' |
<store>Kape & Tinapay</store>
<rule>Grade < 75 means remediation</rule>
For longer text with many special characters, like code, use a CDATA section, where everything is taken literally: