A Simple Document

The easiest way to understand what XML is and what it can do is to work with a concrete example. Listing 2.1 shows a simple lunch menu (LunchMenu.txt) saved as a plain-vanilla text file.

Listing 2.1. A Simple Lunch Menu
SNL Diner
Lunch Hours: 11:00AM - 2:00PM

Lunch Items
==============================
Cheeseburger* .......... $2.50
Chips .................. $1.25
Pepsi .................. $.75

Special Combo (Cheeseburger,
  Chips, & Pepsi) ...... $4.50

* Soy burger available on
request.

This text file is clearly designed to be read by humans. The actual information content (such as item names and prices) is mixed in with characters and whitespace that serve only to make the layout more aesthetically pleasing. But what if this same information needed to be presented on the World Wide Web, or had to be stored in a database? Keeping a single text file up-to-date is no problem, but keeping three or four copies of the same data synchronized becomes cumbersome in a hurry.

This type of application is precisely what XML was designed to do. Listing 2.2 shows the information from LunchMenu.txt reformulated as an XML document.

Listing 2.2. XML Version of Lunch Menu
<?xml version="1.0" encoding="UTF-8"?>
<restaurant>
  <name>SNL Diner</name>
  <menu type="Lunch" start-time="11:00AM"
      end-time="2:00PM">
    <items>
      <item id="L1">
        <name>Cheeseburger</name>
        <price>$2.50</price>
        <note>Soy burger available on request.</note>
      </item>
      <item id="L2">
        <name>Chips</name>
        <price>$1.25</price>
      </item>
      <item id="L3">
        <name>Pepsi</name>
        <price>$.75</price>
      </item>
      <combo id="C1">
        <name>Special Combo</name>
        <item ref="L1"/>
        <item ref="L2"/>
        <item ref="L3"/>
      </combo>
    </items>
  </menu>
</restaurant>

Several things become immediately apparent when comparing the XML document to the original text file:

  • The XML version is twice as long.

  • The text version is much more attractive.

  • The XML version includes information that is obviously not for human consumption.

It is important to realize that XML documents are not intended to be read by humans. XML syntax was designed to be extremely easy for machines to parse. Other technologies (such as XSLT or CSS) are provided to make the raw XML presentable to human beings. Using a transformation language like XSLT, it is possible to convert the XML document from Listing 2.2 into a text file (like the one in Listing 2.1), an HTML document, a series of SQL statements, or any other text-based language.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.240.225