XML Syntax

Home » Scripting » XML » XML Syntax

XML Syntax

A sample of what XML can create

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The first line in the document: The XML declaration, you may also find it called the XML prologue, should always be included. It defines the XML version of the document. In this case the document conforms to the 1.0 specification of XML:

<?xml version="1.0" encoding="UTF-8"?>

The second tag element right after the XML declaration is the root element that contains all the other elements.

<note>

The next lines define the child elements of the root.

<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

The last line defines the end of the root element:

</note>

All XML elements must have a closing tag

In HTML some elements do not have to have a closing tag. The following code is legal in HTML as it is less strict than XML:

<p>The first paragraph
<p>The second paragraph

In XML all tags must be closed

<p>The first paragraph</p>
<p>The second paragraph</p>

XML tags are case sensitive

As some of you probably know you can get away with murder when using html, but xml is case sensitive. The tag <letter> is not the same as <Letter>. Opening and closing tags must therefore be written with the same case

<subject>This is wrong</Subject>
<subject>This is correct</subject>

All XML elements must be properly nested

In XML all elements must be properly nested within each other like this

<b><i>This text is bold and italic</i></b>

All XML documents must have a root tag

All XML documents must contain a single tag pair to define the root element.

All XML documents must contain a single tag pair to define the root element.

<root>
  <child>
    <subchild>
    </subchild>
  </child>
</root>

Attribute values must always be quoted

Another thing that is different from HTML is that all attribute values need to be contained in quotes.

<?xml version="1.0"?>
<note date="12/11/99">

Those are the main syntax rules you need to respect in order to create valid XML files.