XML Tutorial menu

XML Syntax Rules

XML has a few strict rules. A document that follows all of them is called well-formed.

The XML Prolog

The first line is usually the prolog (also called the XML declaration):

Example

xml
<?xml version="1.0" encoding="UTF-8"?>
<note>Bring your laptop to class.</note>

It is optional, but if you write it, it must be the very first thing in the file, with nothing before it, not even a space.

The Rules

RuleCorrectWrong
Every element must be closed<p>Text</p><p>Text
Tags are case sensitive<City>Karachi</City><City>Karachi</city>
Elements must nest properly<b><i>Hi</i></b><b><i>Hi</b></i>
One root element<root>...</root>Two top-level elements
Attribute values in quotes<price cur="PKR"><price cur=PKR>

An empty element can close itself: <br/> or <photo src="ali.jpg"/>.

Well-formed Example

Example

xml
<?xml version="1.0" encoding="UTF-8"?>
<order id="1045">
  <customer>Bilal Ahmed</customer>
  <items>
    <item qty="2">Notebook</item>
    <item qty="1">Geometry Box</item>
  </items>
  <delivered/>
</order>

Every tag is closed, nested correctly, quoted and inside the single root <order>.

What Happens with an Error?

Unlike HTML, XML programs stop at the first mistake. If you open this in a browser:

Example

xml
<order>
  <customer>Bilal Ahmed</Customer>
</order>
Output
XML Parsing Error: mismatched tag. Expected: </customer>.
Line Number 2, Column 24

This strictness is a good thing. It means every program reads the same XML in exactly the same way.

Entity References

Some characters have special meaning in XML. Inside text, write them as entities:

CharacterEntityName
<&lt;less than
>&gt;greater than
&&amp;ampersand
"&quot;double quote
'&apos;apostrophe

Example

xml
<rule>Marks &lt; 40 means fail &amp; repeat the course.</rule>
Output
Marks < 40 means fail & repeat the course.

< and & are the two you must always escape. Using them directly is an error.

CDATA Sections

If you have a lot of text with special characters, such as code, wrap it in CDATA. The parser does not read inside it:

Example

xml
<example><![CDATA[
  if (a < b && b < c) { alert("ok"); }
]]></example>

Comments and White Space

Comments look the same as in HTML:

Example

xml
<!-- This is a comment -->

Do not put -- inside a comment. Also, unlike HTML, XML keeps the spaces inside your text exactly as you wrote them.

Naming Rules

  • Names can contain letters, numbers, hyphens, underscores and dots
  • Names must start with a letter or an underscore
  • Names cannot contain spaces
  • Names cannot start with "xml" in any case

Good names are short and clear: <first_name>, <order-date>, <price>.

Exercise

Exercise

Which of these is well-formed XML?

Learn XML with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp