1. Computing

Discuss in my forum

XML Tutorial - The Declaration and Root Element

Understanding the Basic Rules of XML

From

Many people are stuck trying to abide by the rules of XML. The truth is an XML file may work perfectly even if the scripting does not support all the rules. So you might ask, why bother following XML rules?

By definition, a well-formed document has the minimum criteria necessary for all parsers to interpret the file. While it may seem the XML file works, with some browsers it may fail to load. Concentrating on the structure of your file insures everyone can read it. The rules of designing in XML are not complicated once broken down. Reviewing some of the basic rules of composition in the XML language may help unravel the mystery behind designing a well-formed document. A good place to begin is with the declaration and root element.

XML Rule #1: Making a Declaration

Computers are dumb. They need instructions. That is where the XML declaration comes into play.


‹?xml version= “1.0”›

This is the bare essential declaration statement and the first line of every XML document. The declaration is a processing instruction that tells the browser, “Watch for XML.”

XML Rule #2: Root Elements

All XML documents must have one root element that contains all other elements. Think of the root element as a filing cabinet. A filing cabinet keeps all the files together so there is no chaos. Essentially, that is the job of the root element too. A root element is a container that packages the individual elements of the XML document. For this example, the root element is ‹message.

‹?xml version= “1.0”›
‹message›- root element

The name of the element must immediately follow the start tag (<). That means no spaces between the name and ‘<’. If you are creating a root element called message, it must read:

‹message› not ‹ message›

All Elements Must have an Opening and Closing Tag

XML documents work as in hierarchical structure, what is often referred to as a tree structure. What opens must close; this means all opening tags must also have closing tags.

‹?xml version= “1.0”›
‹message›- root element
‹/message› - root element closing tag

Most web browsers will forgive the closing tag transgression in HTML. In XML, it is absolute. If you fail to incorporate a closing tag into the structure of your XML, you will confuse the computer. The name of the element in the closing tag must match the opening tag exactly.

‹MESSAGE›
‹message›
‹/messages›

XML sees all three of these tags differently. It will only recognize open and closing tags that match precisely.

Once you understand these two key features, The Declaration and Root Element, you have the base structure for an XML page.

©2013 About.com. All rights reserved.