XML syntax rules with examples

XML is strict: one mistake and a parser rejects the whole file. These are the rules every XML document must follow.

Open the tool: XML Validator

The rules of well-formed XML

  • There is exactly one root element.
  • Every start tag has an end tag, or is self-closing like <br/>.
  • Tags close in the reverse order they were opened.
  • Names are case-sensitive and cannot start with a number.
  • Attribute values are always in quotes, and each attribute appears once per tag.
  • & and < in text are written as &amp; and &lt;.

Namespaces

A namespace keeps element names from different vocabularies apart. Declare it with xmlns:prefix="URI" on an element, then use prefix:name in that element and its children. A default namespace, xmlns="URI", applies to all unprefixed elements, which is why plain XPath like //loc finds nothing in a sitemap.

CDATA and comments

Inside <![CDATA[ … ]]> you can write < and & freely, which is handy for code. Comments are written <!-- like this --> and may not contain two hyphens in a row.