How to Write Your First XML Document

Creating a File in XML – Part 1

Writing in XML is not difficult. The XML language is a skill that most anyone can master. The hardest part about learning anything new is getting started. Creating a document in a computer language is best done step-by-step. Working through the basics of writing in XML will help you develop a routine. Once you write the first XML file, you will see the system is easy and flexible. The primary purpose of XML is to contain data that can be accessed by the processor.

Take a look at this small inventory list for a store.

Inventory
Bikes
24-inch Boys Mountain Bike  $200
24-inch Boys Cruiser Bike      $150

Skateboards
Acme Sportsmen Skateboard $75
Deluxe Boys Skateboard        $35

1. Write a Declaration Statement

Declarations provide information to the browser, such as language. A barebones XML declaration statement only requires the language and version. This is enough to establish the page as an XML document. Additional options include encoding and standalone status.

<?xml version= "1.0"?>

2. Create a Root Element

The root element is a container that holds all other elements. It is the first elemental tag for your XML file.

<?xml version= "1.0"?>
<inventory>
</inventory>

Get in the habit of closing your elements as you write them. XML requires closing tags for all elements. Writing both tags at the same time ensures well-formed code and helps to control the structure of the XML.

3. Establish the Child Elements

Child elements nest inside the root element. In an inventory listing, you might create sections for different inventory categories. In the example, we have bikes and skateboards.

<?xml version= "1.0"?>
<inventory>
  <bikes>
  </bikes>
  <skateboards>
  </skateboards>
</inventory>

4. Add Subchild Elements to Hold the Data

Subchild elements nest inside of child elements to hold data you want to store. For this example, there are two models of bikes and two of skateboards. One straightforward format for this list involves nesting additional elements inside the subchild to provide more information for each model, such as price.

<?xml version= "1.0"?>
<inventory>
  <bikes>
    <model>24-inch Boys Mountain Bike
      <price>$200.00 </price>
    </model>
    <model>24-inch Boys Cruiser Bike
      <price>$150.00 </price>
    </model>
  </bikes>
  <skateboards>  
    <model> Acme Sportsmen Skateboard
      <price>$75.00 </price>
    </model>
    <model> Deluxe Boys Skateboard
      <price>$35.00</price>
    </model>
  </skateboards>
</inventory>

This is just one way to work the XML code for this file. Another method would involve using attributes with the elements to identify each section. The advantage of attributes comes when you create formatting for the XML code. In next article we will create the same file, but use attributes with the elements.