XML is a framework for storing information in a tree. The XML document must exactly have one root tag and must have a start-tag (< >) and end-tag (</>). An XML document must adhere to the XML syntax rules, or it is not a valid document. Figure 1 is a well-formed XML document.
Figure 1. A Well-Formed XML Document
<person> <name>Steve Long</name> </person>
|
In addition, text can be contained in the root tag. These are called attributes. For example, Figure 2 shows a sample XML document in which attributes are contained in the root tag.
Figure 2. Using Attributes in an XML Document
<car make="chevrolet"> <model>cavalier</model> <year>2005</year> </car>
|
XML
requires that you properly nest elements in your XML document.
Overlapping cannot occur, and as mentioned earlier, you need to end your
XML with the end-tag (</>). Figure 3 is not a well-formed XML document. You will see that the <year> element overlaps the <car> element.
Figure 3. Not a Well-Formed XML Document
<car>hyundai<year>1997</year></car>
|
XML also has the flexibility to contain empty data. For example, in Figure 4, you will see that there is no price available for the car. An empty-element tag resembles a start-tag but contains a slash just before the closing angle bracket.
Figure 4. Empty Data Usage
<car make="chevrolet"> <model>cavalier</model> <year>2005</year> <price /> </car>
|
Notice that the price does not have an end-tag (</>). That’s because in XML there are different ways to specify the ending of a tag.
<price></price>
<price />
<price/>
XML documents must
conform to syntax rules. Here are some of the rules to follow when you
are creating a well-formed XML document.
All attribute
values are quoted with either single (‘) or double (“) quotes. Single
quotes close a single quote, and double quotes close a double quote.
Tags may be nested but must not overlap. Each nonroot element must be completely contained in another element.
Empty
elements may be marked with an empty-element (self-closing) tag, such
as <NoData/>. This is equal to <NoData></NoData>.
Element names are case-sensitive.
XML Examples
<person>
<name>Steve Long</name>
</person>
<car make="chevorlet">
<model>cavalier</model>
<year>2005</year>
<price/>
</car>
<root>
<customer id="17" firstname="Bob" lastname="Smith">
<address type="home" address1="763 Main Street" city="Anytown"
state="CA" zipcode="93762"/>
<order id="17">
<line_item part_no="12" qty="1" price="12.99"/>
<line_item part_no="73" qty="2" price="6.95"/>
<line_item part_no="17" qty="1" price="2.95"/>
</order>
</customer>
</root>