CodeMIRAI
0 XP

Syntax rules

2 min read 8 runnable examples Quiz included

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
<?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

XML
<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

XML
<p><b>Correctly nested</b></p>
XML
<p><b>Wrongly nested</p></b>

The second fails: inner elements must close before outer ones.

4. Tags are case-sensitive

XML
<Message>Hello</message>

<Message> and </message> don't match.

5. Attribute values must be quoted

XML
<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:

CharacterEntity
<&lt;
>&gt;
&&amp;
"&quot;
'&apos;
XML
<formula>5 &lt; 10 &amp;&amp; 10 &gt; 5</formula>

For longer text full of special characters, a CDATA section is read literally:

XML
<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.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.