XML Notes

Table of Contents

Section 4: XML Syntax

An example XML document:

<?xml version="1.0"?>
<note>
  <to>John</to>
  <from>Peter</from>
  <heading>Reminder</heading>
  <body>Do not forget to send me the data</body>
</note>

The first line in the document, the XML declaration, must 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"?>

The next line defines the first element of the document (the root element):

<note>

The next 4 lines define the child elements of the root (to, from, heading, and body):

<to>John</to>
<from>Peter</from>
<heading>Reminder</heading>
<body>Do not forget to send me the data</body>

The last line defines the end of the root element:

</note>

In XML, all elements must have a closing tag, unlike HTML which tends to be loose in its structure. While the use of closing tags even in HTML is highly suggested data will still display if tags remain open as in the following example:

<p>This is a paragraph
<p>This is another paragraph

In XML, however, the above code sample would prevent the page from displaying as the tags are not closed. The following is the correct way to close the tags shown above so that your XML file will display correctly:

<p>This is a paragraph</p>
<p>This is another paragraph</p>

When creating XML files, you must remember that all tags are case sensitive; therefore the tag <Note> and <note> are two different tags. Opening and closing tags in XML must always be written in the same case:

Correct:

<note>This is a note</note>

<Note>This is a note</Note>

Incorrect:

<note>This is a note</Note>

<Note>This is a note</note>

All XML items must be properly nested within each other, unlike standard HTML.

Correct:

<b><i>This is correct</i></b>

<i><b>This is correct</b></i>

Incorrect:

<b><i>This is incorrect</b></i>

<i><b>This is incorrect</i></b>

All XML tags must also have a root tag. All XML documents must contain a single tag pair to define the root element. All other elements must be nested within the root element. All elements can have sub (child) elements. Sub elements must be in pairs and correctly nested within their parent element:

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

XML elements can have attributes in name/value pairs just like in HTML. In XML the attribute value must always be quoted. Study the two XML documents below. The first one is correct, the second is incorrect:

Correct:

<?xml version="1.0"?>
<note date="12/11/02">
  <to>John</to>
  <from>Peter</from>
  <heading>Reminder</heading>
  <body>Don't forget to send me the data</body>
</note>

Incorrect:

<?xml version="1.0"?>
<note date=12/11/02>
  <to>John</to>
  <from>Peter</from>
  <heading>Reminder</heading>
  <body>Don't forget to send me the data</body>
</note>