About Me

Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Friday, 13 April 2012

XML Tree - Sibling A sibling relationship exists when two elements have the same parent. There are no brothers or sisters in XML, only siblings. Advertise on Tizag.com Finding Your Siblings To find siblings in an XML document, look for elements that are on the same level of the tree and have the same parent. Who is the sibling of snack? XML Code, lemonade.xml: $2.50 20 $1.50 10 $4.50 60 drink is the sibling of snack. If you look at the tree structure, you can clearly see that the elements drink and snack, of the lemonade.xml document, share the same parent, inventory. XML Tree:

XML Tree - Sibling

A sibling relationship exists when two elements have the same parent. There are no brothers or sisters in XML, only siblings.

Finding Your Siblings

To find siblings in an XML document, look for elements that are on the same level of the tree and have the same parent.
Who is the sibling of snack?

XML Code, lemonade.xml:

<inventory>
 <drink>
  <lemonade>
   <price>$2.50</price>
   <amount>20</amount>
  </lemonade>
  <pop>
   <price>$1.50</price>
   <amount>10</amount>
  </pop>
 </drink>
 
 <snack>
  <chips>
   <price>$4.50</price>
   <amount>60</amount>
  </chips>
 </snack>
</inventory>
drink is the sibling of snack.
If you look at the tree structure, you can clearly see that the elements drink and snack, of the lemonade.xml document, share the same parent, inventory.

XML Tree:

XML Tree - Child

XML Tree - Child

When a man loves a woman very, very much, sometimes a kid shows up. This kid is the child of the man and woman.

In XML, an element can have many or no children. Element A is the child of element B when:
  • Element A is contained within element B and is exactly one level below element B.
In other words, B is the parent of A. In this example XML document there are three child relationships. Can you find them?

XML Code:

<a>
 <b>
  <c>
   <d>
   </d>
  </c>
 </b>
</a>
  • Element b is the child of element a.
  • Element c is the child of element b.
  • Element d is the child of element c.

Do You Know Where Your Children Are?

To find the children of element A, look between A's opening and closing tags. If there are elements which are only contained by element A, then they are A's children elements.
Can you find the children elements of chips?

XML Code, lemonade.xml:

<inventory>
 <drink>
  <lemonade>
   <price>$2.50</price>
   <amount>20</amount>
  </lemonade>
  <pop>
   <price>$1.50</price>
   <amount>10</amount>
  </pop>
 </drink>
 
 <snack>
  <chips>
   <price>$4.50</price>
   <amount>60</amount>
  </chips>
 </snack>
</inventory>
price and amount are the children of chips.
If it helps, you can always think of an XML document in a tree structure. Here, we have highlighted the children of chips in our lemonade.xml document.

XML Tree:

XML Tree - Parent

XML Tree - Parent

In real life a person can have multiple parents, especially if the parents divorce and remarry. Thankfully, the relationship in XML is less complicated.

Each XML element can have at most one parent. XML can pull this off because an XML element does not require another element to reproduce (OK, that was a silly joke; I apologize).
Element A is the parent of element B when :
  • Element B is contained within element A and element A is exactly one level above element B.
In other words, the parent element A is the ancestor of element B. Below is an example with 3 parent relationships.

XML Code:

<a>
 <b>
  <c>
   <d>
   </d>
  </c>
 </b>
</a>
The element d is contained by element a, b and c, but only the element c is exactly one level up in the XML Tree, making c the parent of d.
Questions: What are the other parent relationships in this XML document?
Answer:
  • b is the parent of c
  • a is the parent of b

Who's the Parent?

Usually an XML document is indented in such a way as to make finding an element's parent very easy. However, if the indentation is done poorly there is a simple trick to determine an element's parent. Start at the element in question and move up towards the start of the file. The first opening tag that you reach that does not have a corresponding closing tag is the parent.
Can you find the parent element of lemonade in our lemonade.xml document.?

XML Code, lemonade.xml:

<inventory>
 <drink>
  <lemonade>
   <price>$2.50</price>
   <amount>20</amount>
  </lemonade>
  <pop>
   <price>$1.50</price>
   <amount>10</amount>
  </pop>
 </drink>
 
 <snack>
  <chips>
   <price>$4.50</price>
   <amount>60</amount>
  </chips>
 </snack>
</inventory>
drink is the parent of lemonade.
Here is a the XML Tree of the parental relationship between drink and lemonade.

XML Tree:

Bonus: Which element is the parent of snack?
Answer: inventory.

XML Tree - Descendant

XML Tree - Descendant

Any children that you have are your descendants. Any children that your children have are also your descendants. It doesn't matter how far down the family tree these children are; they will always be your descendants.

A descendant relationship is similar in XML. Element A is the descendant of element B if the following is true:
  • Element A is contained within element B.

Is an Element a Descendant?

If you are determining if one element is the descendant of another element, you will need to find the opening and closing tags of both elements to determine the relationship.
We have highlighted inventory and lemonade in our lemonade.xml document; try to determine determine which element is the descendant.

XML Code, lemonade.xml:

<inventory>
 <drink>
  <lemonade>
   <price>$2.50</price>
   <amount>20</amount>
  </lemonade>
  <pop>
   <price>$1.50</price>
   <amount>10</amount>
  </pop>
 </drink>

 <snack>
  <chips>
   <price>$4.50</price>
   <amount>60</amount>
  </chips>
 </snack>
</inventory>
lemonade is the descendant of inventory. This situation was a little tricky because lemonade is contained within another element, drink. However, it doesn't matter how far down the XML Tree an element is. If it's contained by another element, then it is that element's descendant.
Here is a graphical representation of the relationship between inventory and lemonade. You can clearly see that lemonade is the descendant.

XML Tree:

Bonus Question: What are the descendants of lemonade?
Answer: price and amount.

XML Tree - Ancestor

Anyone that came before you in your family tree is your ancestor. This means your mom, dad, grandfather and great-great-great-grandmother are all your ancestors.


Although it may seem strange to some, XML has adopted this terminology to define relationships between various XML elements in the same "family". Element A is the ancestor of element B if the following is true:
  • Element B is contained within element A.

Determining Ancestry

If you are trying to eyeball if one element is an ancestor of another element, then you are going to need to find the opening and closing tags of both elements to determine the relationship.
We have highlighted pop and amount in our lemonade.xml document; you must determine which element is the ancestor.

XML Code, lemonade.xml:

<inventory>
 <drink>
  <lemonade>
   <price>$2.50</price>
   <amount>20</amount>
  </lemonade>
  <pop>
   <price>$1.50</price>
   <amount>10</amount>
  </pop>
 </drink>

 <snack>
  <chips>
   <price>$4.50</price>
   <amount>60</amount>
  </chips>
 </snack>
</inventory>
If you said that pop was the ancestor of amount because pop contains amount, then you're right! Here's a graphical representation of the relationship. If you think of it just like a family tree, it becomes a lot easier!

XML Tree:

What are the other elements that are the ancestor of the highlighted amount? If you said drink and inventory, you're right! That's because drink contains amount and inventory also contains amount.

XML Tree:

Tip: The root element of an XML document is the ancestor of every element in the document. This is because all the elements are contained by the root element, by definition of a well-form XML document.

XML Family Tree

XML Family Tree

You may have seen a lot of XML material make references to descendants, children, parents, or even great grandchildren and wondered to yourself, "Am I reading a family tree or am I learning XML?" The terminology that XML uses to describe the various relationships in a document can be confusing at first, which is why we wrote a set of lessons to clearly explain and show the most commonly used relation terms.

XML - The Tree Structure

The great benefit about XML is that the document itself describes the structure of data. If any of you have researched your family history, you have probably come across a family tree. At the top of the tree is some early ancestor and at the bottom of the tree are the latest children.
With a tree structure you can see which children belong to which parents, which grandchildren belong to which grandparents and many other relationships.
The neat thing about XML is that it also fits nicely into this tree structure, often referred to as an XML Tree.
Before you even think about matching up these tree terms with their XML counterparts, it might be helpful to see a real XML document converted into a tree structure. The lemonade.xml document we will be using was created by a particularly enterprising kid to keep inventory of her lemonade stand.

XML Code, lemonade.xml:

<inventory>
 <drink>
  <lemonade>
   <price>$2.50</price>
   <amount>20</amount>
  </lemonade>
  <pop>
   <price>$1.50</price>
   <amount>10</amount>
  </pop>
 </drink>

 <snack>
  <chips>
   <price>$4.50</price>
   <amount>60</amount>
  </chips>
 </snack>
</inventory>

XML Tree:

As you can see from the XML document, inventory is the root element. When we convert the document over to a tree format, we can see that the inventory element is at the top of the tree. In other words, all other elements are a descendent of the inventory element.
Construction of an XML tree isn't all that hard to do, as long as you follow some basic rules.

XML Tree Rules

We've written up a set of rules to use in figuring out if an element is a child or parent of another element. With these basic rules, you can figure out the relationship of just about any two elements in an XML document.
  • Descendants: If element A is contained by element B, then A is a descendant of B. In the lemonade.xml example, every element is a descendant of inventory because inventory is the root element.
  • Ancestors: If an element B contains element A, then B is an ancestor of A. In the lemonade.xml example, drink is the ancestor of lemonade and pop.

XML Family Tree Continued

The next few lessons will go into more detail about descendant, ancestor, child, parent and sibling relationships in an XML document. If you are still attempting to grasp the notion of the XML Tree structure, we recommend that you carefully read through each of these lessons.

XML Processor

XML Processor

An XML processor is a necessary piece of the XML puzzle. The XML processor takes the XML document and DTD and processes the information so that it may then be used by applications requesting the information.

What the Processor Does

The processor is a software module that reads the XML document to find out the structure and content of the XML document. The structure and content can be derived by the processor because XML documents contain self-explanatory data.

Any Use to the Casual XML Coder?

The XML processor is probably no use to the casual XML coder. The processor is simply a bridge between the XML document you write and the application that will be using it in the end. When you validate your XML you put your XML through a processor, which then gives it to an application, which then spits out the results to your monitor.

XML Documents: Valid Versus Well-Formed

XML Documents: Valid Versus Well-Formed

In XML, there are three ways to measure a document's validity: valid, well-formed, and broken. You probably only care that your XML document works, but knowing the requirements for each kind of validity may shed some light on problems that arise in the future.

Well-Formed XML

A well-formed XML document has to follow several rules that most other markup languages also follow. These are generic rules that must be followed for a document to be well-formed, as well as valid. The rules are as follows:
  • One Root Element - The XML document may only have one root element. See our Root Element Lesson for more information.
  • Proper Nesting - XML elements must be closed in the order they are opened. See our Nesting Lesson for more information.
  • Well-Formed Entities - Any entities that are referenced in the document must also be well-formed. See our Entity Lesson for more information.
The first example below is incorrect, and the second is well-formed. Try to figure out the error in the first example.

Broken XML Code:

<email>
 <to>Mr. Garcia
  <body>Hello there! How are we today?</to>
 </body>
</email>

Well-Formed XML Code:

<email>
 <to>Mr. Garcia</to>
 <body>Hello there! How are we today?</body>
</email>
The error in the first example was:
  • The document suffers from improper nesting. The body element was opened inside the to element, yet body was not closed before the to element was closed!

Valid XML

First and foremost, a valid XML document must be well-formed. The well-formed requirement (see above) should be fairly straightforward. The key to making an XML document leap from well-formed to valid is slightly more difficult.
To be valid, an XML document must be validated. A document cannot be validated unless a Document Type Definition (DTD), internal or external, is referenced for the XML processor. For the XML document to be valid, it must follow all the rules set forth in the DTD.

Broken XML Files

Broken XML documents are simply those which fail to follow the rules required for a document to be either well-formed or valid. Many of the XML editors on the market today (free and purchased) are an excellent source of help when attempting to fix small errors in your XML code.

XML Namespace

XML Namespace

XML was designed to be a very robust markup language that could be used in many different applications. However, with XML being able to communicate between so many different platforms, there is one problem that tends to occur.

XML Element Overlap

When you are creating new elements, there is the chance that the element's name already exists. Imagine someone was creating a health-related XML document that included XHTML (that's HTML that is also valid XML).

XML Code:

<?xml version="1.0" encoding="ISO-8859-15"?>
<html>
<body>
<p>Welcome to my Health Resource</p>
</body>

<body>
<height>6ft</height>
<weight>155 lbs</weight>
</body>

</html>
Here, we have two very different elements that want to use the same name: body. The solution to this problem is to create XML Namespaces, which will differentiate between these two similarly named elements!

XML Namespace Syntax

The XML namespace is a special type of reserved XML attribute that you place in an XML tag. The reserved attribute is actually more like a prefix that you attach to any namespace you create. This attribute prefix is "xmlns:", which stands for XML NameSpace. The colon is used to separate the prefix from your namespace that you are creating.
As we mentioned in our XML Attribute Lesson, every XML attribute must be set equal to something. xmlns must have a unique value that no other namespace in the document has. What is commonly used is the URI (Uniform Resource Identifier) or the more commonly used URL.
To rectify the overlap in our health XML document, we will be using the W3C's XHTML URL and a made up URI for our second body element. Both the namespace attribute and its use in our document has been highlighted in red.

XML Code:

<?xml version="1.0" encoding="ISO-8859-15"?>
<html:html xmlns:html='http://www.w3.org/TR/xhtml1/'>
<html:body>
<html:p>Welcome to my Health Resource</html:p>
</html:body>

<health:body xmlns:health='http://www.example.org/health'>
<health:height>6ft</height>
<health:weight>155 lbs</weight>
</health:body>

</html:html>
By placing a namespace prefix before our elements, we have solved the overlapping problem!
If you are feeling inquisitive, feel free to check out W3C's Namespace Document for a very in-depth look at XML namespaces. Be warned; it is quite long and dry!

XML Nesting

XML Nesting

In a prior lesson, we showed an example of an XML document. The file contained a root element and a couple of elements that were inside the root element.


When an element appears within another element, it is said that the inner element is "nested". The term nested can be related directly to the word "nest". If an element is nested within another element, then it is surrounded, protected, or encapsulated by the outer element (chirp chirp!).

XML - Why We Nest

Besides being such an easy term to understand, nesting also serves a wonderful purpose of keeping order in an XML document. Much like parentheses in a math problem, elements must be closed in the order that they are opened.
This means that an element which is nested inside another element must end itself before the outer element. Below are two example XML documents (A & B). One is properly nested and the other has a small problem.

A) XML Code:

<phonebook>
 <number>
 <name>
 </number>
 </name>
</phonebook>

B) XML Code:

<phonebook>
 <number>
 <name>
 </name>
 </number>
</phonebook>
Did you figure it out? Well if you decided that example B was the properly nested document, then you are correct! All elements are closed in the order that they were opened. Those elements which were opened first are closed last.
Did you spot the problem with example A? The name element is nested within the number element, yet the number element is closed before name! Example B is what example A must look like to be a well-formed XML document.

Nesting Rules

To think of nesting in plain English, follow this rule: elements opened first must be closed last. That means that the root element, the first element in an XML document, must also be closed last. Nested elements, ones that occur in the middle of the document, must be closed before those that came before them.
Once you get the hang of nesting, you'll have no problem creating XML documents. However, this is a common mistake new XML programmers make, so pay close attention to this lesson!

XML Prolog

XML Prolog

The prolog is an optional component of the XML document. If included, the prolog must be appear before the root element. A prolog consists of two parts: the XML declaration and the Document Type Declaration (DTD). Depending on your needs, you can choose to include both, either, or neither of these items in your XML document. The DTD is most oftenly used, so we will discuss its use and purpose first.

XML Document Type Declaration (DTD)

The Document Type Declaration is a file that contains the necessary rules that the XML code in this file must follow. You may think of the DTD as the grammar that the XML document must abide by to be a valid XML file.
In later lessons we will discuss how to create your own DTD, which will allow you to make your own XML rules. For now we will simply show you how to reference an existing DTD file.

Referencing an External DTD

There are two type declarations that may be used to reference an external DTD: PUBLIC and SYSTEM. When creating an XML document under the rules of a publicly distributed DTD, use PUBLIC. Otherwise, use the SYSTEM type declaration.
The example below shows a prolog that would be used for an HTML document that is using an XML prolog. The DTD is publicly available thanks to the W3C.

XML Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Let's take a look at each piece of this external DTD reference.
  • !DOCTYPE - Tell the XML processor that this piece of code defines the Document Type Definition
  • html - Specifies the root element of the XML document. Here our example is an HTML file, which has <html> as the root element.
  • PUBLIC - Specifies that this a publicly available DTD.
  • "-//W3C//D..." - The definition of the public document. Describing this is beyond the scope of this tutorial.
  • "http://www.w3.org/..." - The physical location of the DTD. Notice how this DTD resides on w3's servers.

The XML Declaration

This is where you define what version of XML you are using. The current version is 1.0, which it has been for quite some time now. Check out the most recent XML version at w3.org.

XML Code:

<?xml version="1.0"?>
The declaration is not absolutely necessary, but should be included anyways.

XML & DTD Declaration Together

If you were to include both an XML declaration and a DTD declaration on an XML document then you would place the XML declaration first, followed by the DTD declaration. We have done just that in the example below.

XML Code:

<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Be sure to include the optional prolog when you want to run your document through an XML processor to check for validity. If you have a valid DTD, simply use the free markup validation tool at W3C.

XML Comment

XML Comment

A comment is used to leave a note or to temporarily edit out a portion of XML code. Although XML is supposed to be self-describing data, you may still come across some instances where an XML comment might be necessary.

XML Comment Syntax

XML comments have the exact same syntax as HTML comments. Below is an example of a notation comment that should be used when you need to leave a note to yourself or to someone who may be viewing your XML.

XML Code:

<?xml version="1.0" encoding="ISO-8859-15"?>
<!-- Students grades are updated bi-monthly -->
<class_list>
 <student>
  <name>Robert</name>
  <grade>A+</grade>
 </student>
 <student>
  <name>Lenard</name>
  <grade>A-</grade>
 </student>
</class_list>

XML Commenting out XML

For many different reasons, sometimes you might want to temporarily remove some XML code from your XML document. XML Comments let you do this easily, as this example below shows.

XML Code:

<?xml version="1.0" encoding="ISO-8859-15"?>

<class_list>
 <student>
  <name>Robert</name>
  <grade>A+</grade>
 </student>
<!--
 <student>
  <name>Lenard</name>
  <grade>A-</grade>
 </student> 
-->
</class_list>

XML Attribute

XML Attribute

XML Attributes are very similar to HTML attributes that you may already have a grasp of. An attribute appears within the opening tag of an element.

XML Attribute Syntax

Unlike in HTML, XML requires that all XML attributes have a value. This means all attributes have to be equal to something! Below is the correct way to create an attribute in XML.

XML Code:

<student active="true">
 <name>Robert</name>
 <grade>A+</grade>
</student>
The attribute active is valid because we set it to a value true. Here is an example of shorthand that is sometimes used in HTML, but is not valid XML.

XML Code:

<student active>
 <name>Robert</name>
 <grade>A+</grade>
</student>
This XML attribute is wrong because it was not set to a value.

XML Attribute Quotation Usage

The types of quotes that you use around your attribute values is entirely up to you. Both the single quote (') and the double quote (") are perfectly fine to use in your XML documents.
The only instance you might want to use one quotation over the other is if your attribute value contains a quotation or apostrophe of its own. Below are a couple of real world examples.

XML Code:

<student nickname='Rob "The Dog"'>
 <name>Robert</name>
 <grade>A+</grade>
</student>

XML Code:

<student group="Pete's Pandas">
 <name>Robert</name>
 <grade>A+</grade>
</student>

XML Tags

XML Tags

As was mentioned quickly in the XML Element Lesson, XML tags signify the opening and closing of an element. The two types of tags are:

  • Opening Tag - <element>
  • Closing Tag - </element>
If you already have a knowledge of how tag works from HTML or other experience, then you can skip this tag lesson.

A Tag Pair

The opening and closing tags are referred to as a tag pair. All data that belongs to a specific element will be appearing within this tag pair.

The Solo Tag

In addition to the standard tag pair, there are elements that contain no text. This means the tag pair can be substituted with a modified opening tag. You may have seen these types of tags in HTML before.
  • Modified opening tag
  • - <element />
Notice that there is a slash after the name of the element. This acts as a signal to the XML processor that this element has completed and is a shorthand for elements that have no data between opening and closing tags.

The Tag Ordering Rule

Every XML tag must be closed in the order that it was opened. If an XML tag was opened inside another element, then it must be closed before the outer element can close. If this rule is not obeyed, an XML processing error will occur. Below are examples of good and bad XML documents. Try to figure out which are valid XML and which violate a rule.

XML Code 1:

<email>
  <to>A. Nony Mouse</to>
 <body>Hey There!</body>
</email>

XML Code 2:

<email>
 <to>A. Nony Mouse
 <from>Bobby</to></from>
  <body>Hey There!</body>
</email>

XML Code 3:

<email>
  <to>A. Nony Mouse</to>
 <from>Bobby</from>
 <body>Hey There!</body>
</email>
The correct XML documents are the first and third examples. The second example does not follow the ordering requirement, as the "to" element is closed before the embedded "from" element". This problem was fixed in the third example by moving the "from" element out of the "to" element.

Indenting and Spacing XML Tags

The error in the above example was rather easy to pick out due to our indentation and spacing. A good rule of thumb is to start a new line before placing a new tag. Also, if a tag is nested, then indent to make this fact clearer.

XML Entity

XML Entity

An entity is a symbolic representation of information. What does that mean? Well, let's imagine for a moment that we want to create an introduction that is included in every single memo that we write. It would be monotonous to have to type out a three sentence introduction for every letter, but not to worry! XML entities can help us out.


With symbolic representation of information, a lot of text, such as, "Hello my name is Tizag.com and I am an artificial intelligence that teaches the general public how to program in web languages for free," can be represented by an entity symbol.

Entity Syntax

You may have used entities in the past. The format of an entity in XML is an ampersand (&), followed by the name of the symbol, and concluded with a semicolon.
  • Generic Entity - &name;
HTML is another markup language that supports entities. Below are some example entities and the information they represent.
  • &copy; = ©
  • &lt; = <
  • &amp; = &
  • &quot; = "

Creating an XML Entity

An entity must be created in the Document Type Definition (DTD). Once you know where to place the entity, the rest is easy. Here is the syntax for creating your own XML entities.
  • <!ENTITY entityName "The text you want to appear when the entity is used">
Below, we have created an entity for the default introduction we want to include on all of our documents.

XML Code:

<!ENTITY intro "Hello
my name is Tizag.com and I am an artificial intelligence that teaches the general public how to program in web languages for free">

Using Your Entity

After the entity has been created in the DTD, it can then be referenced. An example email XML document that uses such an entity would look like:

XML Code:

<!ENTITY intro "Hello
my name is Tizag.com and I am an artificial intelligence that teaches the general public how to program in web languages for free">
<email>
 <to>A. Nony Mouse</to>
 <body>&intro;</body>
</email>
Entities are great for many situations. Such as when you...
  • Use something a lot. If you have a default introduction, signature, or something else that is commonly used, you should use an entity.
  • Change something often. If you have a relatively static document that has one or two pieces of frequently-changing information that are used throughout the document, replace them with entities. You only need to change the value of the entity to change hundreds or maybe even thousands of references that are in your XML document.
  • Are using complex ASCII characters that don't occur on your keyboard: © and ® are easy when you use entities.

XML Element

XML Element

XML is a markup language that is used to store data in a self-explanatory manner. Making the data "self-explanatory" comes about by containing information in elements. If a piece of text is a title then it will be contained within a "title" element.

XML Tag

A tag is just a generic name for a <element>. An opening tag looks like <element>, while a closing tag has a slash that is placed before the element's name: </element>. From now on we will refer to the opening or closing of an element as open or close tags. All information that belongs to an element must be contained between the opening and closing tags of an element.

XML Attribute

Attributes are used to specify additional information about the element. It may help to think of attributes as a means of specializing generic elements to fit your needs. An attribute for an element appears within the opening tag.
If there are multiple values an attribute may have, then the value of the attribute must be specified. For example, if a tag had a color attribute then the value would be: red, blue, green, etc. The syntax for including an attribute in an element is:
  • <element attributeName="value">
In this example we will be using a madeup XML element named "friend" that has an optional attribute age.

XML Code:

<friend age="23">Samantha</friend>

Element Review

  • Elements are used to classify data in an XML document so that the data becomes "self-explanatory".
  • Opening and closing tags represent the start and end of an element.
  • Attributes are used to include additional information on top of the data that falls between the opening and closing tag.

XML - ML Document: The Root Element

ML Document: The Root Element

In any markup language, the first element to appear is called the "root element", which defines what kind of document the file will be. In an HTML file, the <html> tag is the root element. An HTML file will always have the HTML element as the root element, while in an XML file, it can be anything.

In an XML file, there can only be one root element. The root element must encapsulate all other elements--meaning, these other elements must show up after the opening root tag and before the closing root tag. Here is an example of an XML document with the root element "phonebook".

XML Code:

<phonebook>
 <number>
 </number>
 <name>
 </name>
</phonebook>
Notice how the root element "phonebook" surrounds the other elements in XML file. Below is a broken XML file. Try to see if you can find what is wrong with this file before reading the caption below.

XML Code:

<phonebook>
 <number>
 </number>
 <name>
</phonebook>
</name>
You should have noticed that the root element "phonebook" did not contain all other elements because the closing name tag </name> is not between the root element tags <phonebook> and </phonebook>.

There Can Be Only One

Another rule for XML files is that only one root element per file is allowed. Our previous example followed this rule, but our example below does not because it has two root elements. What are the two root elements?

XML Code:

<phonebook>
 <number>
 </number>
 <name>
 </name>
</phonebook>
<diary>
 <date>
 </date>
</diary>
If you said the two root elements were "phonebook" and "diary", then you got it right! Phone book is the first element to appear in this file, so it is automatically a root element.
After the phonebook element is closed, no other elements should follow because XML can only have one root element per file. Because the "diary" element did not follow this rule, it transformed this XML file into a lawless, rule-breaking file!

XML Document: Dissection

XML Document: Dissection

Excuse the unpleasant title of this XML lesson, but the name is suited for what we are about to do. In this lesson, we will be taking apart and analyzing each part of an XML document. Consider this an overview of the XML document, and do not be unsettled if you don't understand all that is discussed in this lesson. We will cover all these parts in greater detail throughout the tutorial.

Parts of an XML Document

An XML document is made up of a small group of building blocks. W3C wanted to keep XML simple, and judging by the relatively few components of an XML document, they seem to have succeeded. We have divided the components into sections and subsections.
  • Prolog
    • XML Declaration
    • DTD Declaration
  • Root Element (Document)
    • Elements (Nested Elements)
      • Element Attributes and Values
      • Data
Webpage standards now recommend that an HTML document follow this form, so that they can be considered valid XML. Fun Fact: In an HTML file the root element is <html>.

XML Prolog

The XML prolog is an optional piece of information that must come before the root element when used. There are two pieces that make up the prolog: the XML declaration and the Document Type Declaration (DTD).
The XML declaration states which version of XML you are using, while the DTD describes the rules your XML document must follow. If you are just dying to know more about the DTD and can't wait to read through the lessons as we have laid them out (we won't be offended), check out our XML DTD lesson.

XML Root Element (Document)

The root element, also referred to as the "document", dictates what kind of XML document it is. When creating an HTML file that is XML complaint, the root element will be <html>. The root element must be the first element in an XML document and there can only be one root element per file!

XML Element & Attributes

The meat of an XML document comes from the elements that are contained within the root element. Each element represents a different type of data that is being stored in the document. The element <p> might represent paragraph text, while the element <gif> may contain data for a GIF image.
Although not required, elements often have attributes that are associated with them. XML attributes are similar to HTML attributes in that they have a name:value relationship. An example attribute for an <img> element might be "src", which represents the source location of the image.

XML Element & Attribute Code:

<img src = "C:/MyDocs/Happy.gif"></img>

XML Data

In addition to the information stored in the element itself (attributes), the bulk of data in XML usually appears between the opening and closing tag of an XML element. This is often referred to as the XML's "content". Below, we have an imaginary XML document that stores a story.

XML Code:

<story>
 <author>Jill Doe</author>
 <title>The Truth About the Family</title>
 <page> 
  <paragraph>Here's a story of a lovely lady who...</paragraph>
  <paragraph>...they became the Brady Bunch...</paragraph>
 </page>
</story>
Quick Learning Check:
Can you tell which element is the root element in the above XML code? If you thought <story>, then you were right on the money!

XML Syntax

XML Syntax

If you have already programmed in HTML, XML syntax shouldn't be that much of a leap to grasp. While there are a couple of new items in XML, it is still just a markup language that relies on tags to get the job done.

XML Syntax: Our Example XML Document

This lesson will analyze a real XML file to point out the syntax used to create a Well-Formed XML document. This XML document was used to keep track of students in an Computer Application's Course.

XML Code:

<?xml version="1.0" encoding="ISO-8859-15"?>
<class_list>
 <student>
  <name>Robert</name>
  <grade>A+</grade>
 </student>
 <student>
  <name>Lenard</name>
  <grade>A-</grade>
 </student>
</class_list>

If you spend a few moments reading through the above XML document, you can see it has two students, Robert and Lenard. This simple XML document readily displays the benefits of XML. The data seems to almost describe itself, which is one of the main reasons XML was created!
Let's take a look at XML syntax by looking at the different parts of this document. Note: This is just an overview of XML's syntax and there are links to more information provided in this lesson.

XML Prolog (optional)

I think the only thing not easily understandable in our XML document is that first line with all the symbols and attributes. This rather confusing line in our XML document is referred to as the XML Prolog.

XML Code:

<?xml version="1.0" encoding="ISO-8859-15"?>
This line with special symbols and attributes is what is referred to as the XML declaration. It simply states what version of XML you are using and the type of encoding you are using. Don't worry too much about this line just always include it exactly as we have above. If you are curious, feel free to learn more about ISO 8859.

XML Tag

The XML tag is very similar to that of the HTML tag. Each element is marked with an opening tag and a closing tag. Below, we have highlighted both the opening and closing tags from a piece of our example XML file.

XML Code:

<name>Robert</name>
<grade>A+</grade>
Later in the tutorial, we talk more about XML Tags, including opening tags, closing tags, and all the text inbetween them, which combine to form XML Elements.

XML Elements

XML Elements are the meat and potatoes of XML. They contain the opening and closing tags, child elements, and data. In our XML document the student element is comprised of all of the following information. Notice how it has a couple of child elements.

XML Code:

<student>
 <name>Robert</name>
 <grade>A+</grade>
</student>

XML Editors

XML Editors

These days there are countless editors available on the market, making your choice a difficult one. There are free editors that are probably good for beginner to intermediate XML coders, and there are the $600 XML suites for XML professionals or avid users.

XML Editors - Features

The basic job of an XML editor is to allow you, the XML coder, to create and manipulate XML documents. The basic features you need are syntax highlighting (color codes to make the XML easier to read), some sort of way to validate the XML code that you write, and of course, the ability to create, edit, and save XML documents.

Free XML Editors

There are many free XML editors available for download on the internet. Here are a few we have found useful:

Purchasable XML Editors

If you are looking for a more professional solution and have the money ($50-$600), you may want to purchase one of the following XML editors.

W3C XML Validation Tool

In addition to the software listed above, you can also use online validation tools. Our favorite, a simple and easy-to-use webpage, is the markup validation tool provided by W3C. It can validate XML, as well as any other markup language. Check out W3C's Validation Tool.