About Me

Friday, 13 April 2012

XML - ML Document: The Root Element

ML Document: The Root Element

In any markup language, the first element to appear is called the "root element", which defines what kind of document the file will be. In an HTML file, the <html> tag is the root element. An HTML file will always have the HTML element as the root element, while in an XML file, it can be anything.

In an XML file, there can only be one root element. The root element must encapsulate all other elements--meaning, these other elements must show up after the opening root tag and before the closing root tag. Here is an example of an XML document with the root element "phonebook".

XML Code:

<phonebook>
 <number>
 </number>
 <name>
 </name>
</phonebook>
Notice how the root element "phonebook" surrounds the other elements in XML file. Below is a broken XML file. Try to see if you can find what is wrong with this file before reading the caption below.

XML Code:

<phonebook>
 <number>
 </number>
 <name>
</phonebook>
</name>
You should have noticed that the root element "phonebook" did not contain all other elements because the closing name tag </name> is not between the root element tags <phonebook> and </phonebook>.

There Can Be Only One

Another rule for XML files is that only one root element per file is allowed. Our previous example followed this rule, but our example below does not because it has two root elements. What are the two root elements?

XML Code:

<phonebook>
 <number>
 </number>
 <name>
 </name>
</phonebook>
<diary>
 <date>
 </date>
</diary>
If you said the two root elements were "phonebook" and "diary", then you got it right! Phone book is the first element to appear in this file, so it is automatically a root element.
After the phonebook element is closed, no other elements should follow because XML can only have one root element per file. Because the "diary" element did not follow this rule, it transformed this XML file into a lawless, rule-breaking file!

0 comments:

Post a Comment