XML Structure
In this tutorial, we will learn the XML Structure with the help of examples.
1. Root Element is mandatory in XML
XML document must have a root element. A root element can have child elements and sub-child elements.
For example: In the following XML document,
is the root element and , , and are child elements.
Steve
Paul
Message from teacher to Student
You have an exam tomorrow at 9:00 AM
The following XML document is wrong because it doesn’t have a root element.
Steve
Paul
Message from teacher to Student
You have an exam tomorrow at 9:00 AM
2. XML is case sensitive
XML is a case sensitive language.
For example:
This is valid
Paul
This is invalid
The first letter of closing tag is in capital while the first letter of opening tag is in small, this is an example of invalid XML.
Paul
3. XML Prolog
This line is called the XML Prolog. It is an optional line, however it should be the first line when you mention it. It specifies the XML version and the encoding used in the XML document.
4. Elements should not overlap
All the elements in XML should be properly nested and they should not overlap.
Rick -->Wrong (Not nested properly)
Rick -->Correct (Correctly nested)
5. Attributes in XML
We will discuss XML attributes in detail later. For now, lets see the syntax of attributes. An opening tag in XML can have attributes, these attributes are name & value pairs.
Attribute names are case sensitive and should not be in quotation marks.
Attribute values should be in single or double quotation.
You have an exam tomorrow at 9:00 AM
Here category is the attribute name and message is the attribute value.
Lets take few more examples to see valid and invalid cases of attributes.
A tag can have more than one name & value pairs, however two attribute names cannot be same (see point 5 in the following example)
1. hello -->wrong
2. hello -->wrong
3. hello -->correct
4. hello -->correct
5. hello -->wrong
6. XML elements must have a closing tag
All XML documents must have a closing tag.
hello -->correct
hello -->wrong
7. Comments in XML
This is how a comment should look like in XML document.
8. White-spaces are preserved in XML
Unlike HTML that doesn’t preserve white space, the XML document preserves white spaces.