Elements and the Root Element

An element is defined by a start tag (such as <MyData>) and an end tag (such as </MyData>). Any data you enter between the start and end tags makes up the contents of that element. As you can see in the following example, the document begins with <MyTable> and ends with </MyTable>; all of the syntax you see between these tags makes up the content of the MyTable element:

<?xml version="1.0"?> <MyTable>

<Customer>

<Quarter>Q1</Quarter> <Region>North</Region> <Revenue>25000</Revenue> </Customer> </MyTable>

The concept of tags will be a familiar one to those who have worked with HTML. However, unlike HTML, tags in XML are not predefined. That is to say, the text MyTable has no predefined utility or meaning. You can change that text to Pork and it would be all the same to the XML document. And herein, you stumble on the beauty of XML. XML allows you to create custom tags: tags to which you give definition and purpose. As long as you adhere to a few basic rules, you can create and describe any number of elements by creating your own custom tags. Here are the basic syntactic rules that must be followed when creating elements:

□ Every element must have a start tag, represented by left and right angle brackets (<>), as well as a corresponding end tag represented by a left angle bracket, forward slash, and right angle bracket (</>).

□ Names in XML are case sensitive, so the start and end tags of an element must match in case as well as in syntax. For example, an element defined by the tags <Data> </data> would cause a parsing error. XML would look for the end tag for <Data> as well as the start tag for </data>.

□ You must begin all element names with a letter or an underscore; never a digit. In addition, names that begin with any permutation of xml are reserved and cannot be used.

The MyTable element is the root element for this particular XML document. The root element (which is always the topmost element in an XML document) serves as the container for all of the contents within the document. Every XML document must have one (and only one) root element.

Below the root element, you will see four elements, each one containing its own content. Elements can contain numbers, text, and even other elements.

Elements are normally framed in a parent/child hierarchy. For instance, in the previous example, the Customer element is a child o the MyTable root element. Likewise, the MyTable element is the parent of the Customer element. Following that logic, the Quarter, Region, and Revenue elements are the children of the Customer element. This parent/child hierarchy allows the XML document to describe the structure of the data as well as the content. Later in this chapter, you will discover how this parent/child hierarchy is leveraged to programmatically move around in XML documents.

0 0

Post a comment