Basic XML rules: well-formed and valid XML

Nesting elements

The XML specifications require that within an XML document all elements have to be nested within a root element. If you take the simple example of an address book, the root element could be  <addressBook>. Nested within the root element you may have several <entry> elements containing  address information. . A very basic structure might look something like this:

1
2
3
4
5
6
7
8
<addressBook>
    <entry>
        This is the first entry!
    </entry>
    <entry>
        This is the second entry!
    </entry>
</addressBook>

To explain basic principle of nesting in XML, the Russian ‘Matryoshka doll’ might make a good analogy. The root element is the largest container. All other elements have to be entirely nested within the root element or another element. In a similar way smaller Matryoshka dolls’are nested within bigger ones.


In the address book example,  all <entry> elements are completely nested within the start and end root element. Furthermore, each address entry can other have elements nested in it. For instance, an entry may have <name>  as follows:









1
2
3
4
5
<addressBook>
    <entry>
        <name></name>
    </entry>
</addressBook>

Each entry could have additional elements nested inside it, including house number, street name, town, telephone number, etc. Nesting elements provides additional structure which makes it easier for searching . For instance, consider the following address:

Clark Kent 344 Clinton Street Metropolis 55 50145

As humans we can read each part of the entry and understand what part is the name, the address and the telephone number. A computer does not understand text in the same way as humans do, hence adding more structure provides for this specificity: 

1
2
3
4
5
<entry>
    <name>Clark Kent</name>
    <address>344 Clinton Street Metropolis</address>
    <phoneNr>55 50145</phoneNr>
</entry>

   
 With more elements, even more data can be specified as follows: 

1
2
3
4
5
6
7
8
9
10
11
12
<entry>
    <name>
        <forename>Clark</forename> 
	<surname>Kent</surname>
    </name>
    <address>
       <houseNr>344</houseNr> 
       <street>Clinton Street</street> 
       <town>Metropolis</town>
    </address>
    <phoneNr>55 50145</phoneNr>
</entry>

 

That this data is nested provides important information to the computer. For example, since the  <address> element encloses  <houseNr>, <street> and <town>,  it can be inferred that they belong to the same address.