Syntax rules
An XML document that follows the rules is called well-formed. Break any rule and parsers reject the whole document. Run each example to see the parser's verdict.
1. Exactly one root element
<?xml version="1.0"?>
<notes>
<note>Buy milk</note>
<note>Call Mei</note>
</notes>Everything must live inside a single root (<notes> here). Two top-level elements is an error.
2. Every element must be closed
<list>
<item>Closed properly</item>
<empty/>
<item>Missing a closing tag
</list>Elements with no content can use the self-closing form <empty/>.
3. Tags must nest properly
<p><b>Correctly nested</b></p><p><b>Wrongly nested</p></b>The second fails: inner elements must close before outer ones.
4. Tags are case-sensitive
<Message>Hello</message><Message> and </message> don't match.
5. Attribute values must be quoted
<price currency="EUR" discounted='true'>19.99</price>Single or double quotes are both fine; no quotes is an error.
6. Escape special characters
< and & can't appear raw in text, because they start tags and entities. Use entities:
| Character | Entity |
|---|---|
< | < |
> | > |
& | & |
" | " |
' | ' |
<formula>5 < 10 && 10 > 5</formula>For longer text full of special characters, a CDATA section is read literally:
<code><![CDATA[ if (a < b && b > c) { return true; } ]]></code>The XML declaration
<?xml version="1.0" encoding="UTF-8"?> at the very top is optional but recommended. It states the XML version and character encoding.