Creating a Well-Formed XML Document - Getting a Root Element
(Page 3 of 4 )
After your declaration, you will want to include the opening tag for your root element. The root element is the parent element to all of the other elements in your XML document, and therefore everything is nested within it. A good way to think of this is like the <html> tag in the HTML language. It is the root element in your HTML document, and without it, the document will not work. The <head>, <body> and all other tags begin and end between the opening and closing tags of <html> and </html>. The same goes with your root element. The only difference is that you can make your root element anything you please.
In our previous example, I chose to make <albums> the root element. We chose <albums> over the root <album> because a person might well purchase more than one album, and then where would we be?
Define Your Elements
If you recall from the last article, we had three categories: album, customer, and sales. Within each of these categories, we defined sub-categories, or children. This is what is meant by defining your elements.
Below is a reminder of the hierarchy of elements, including one that we have yet to touch upon:
The parent element - Any time that an element has other elements nested within it, it takes on role of a parent element.
The child element - Any element nested within another element is a child element.
Sibling element - When a parent element has more than one child, these children elements become known as siblings. They share the same level in your hierarchy.
This means that in our document from the previous article, <albums> was the root (and thus parent) of all elements. Album, Customer, and Sales are all parents (and siblings to one another), and all of the subcategories are children of our parents, and siblings to one another.
Here is a look at our XML document, which is now well-formed:
<?xml version="1.0" standalone="Yes"?>
<albums>
<album>
<albuminfo>
<artist></artist>
<genre><genre>
<format></format>
<price></price>
<uniqueID></uniqueID>
<label></label>
<length><length>
<release></release>
</albuminfo>
<customerinfo>
<first></first>
<last></last>
<address>
<email></email>
<phone></phone>
</customerinfo>
<salesinfo>
<uniqueID></uniqueID>
<price></price>
<coupon></coupon>
<shipping></shipping>
<date></date>
<type></type>
</salesinfo>
<totalPrice></totalPrice>
</album>
</albums>
You may notice that this document looks a little different from the one in our previous article. This is because I made some changes to ensure that the document is now well-formed. You will notice that one of the changes I made was to make totalPrice a parent and remove it as a child from salesinfo. I did this in case there were multiple sales.
Next: Well-Formed >>
More XML Tutorials Articles
More By James Payne