Home

Introduction to the Extensible Markup Language

The Extensible Markup Language

Introduction

When you create this type of list, you choose the programming environment of your choice and save the file. You cannot open that file in just any application. You must create and distribute the application to those who want to be able to open a file created by your application. It could be useful to create a type of file using any application of your choice and be able to open that file using another type of application that you may not even know.

Practical LearningPractical Learning: Introducing XML

  1. Start Microsoft Visual Studio and create a new Windows Application named LambdaSquareApartments2
  2. To create a new form, on the main menu, click PROJECT -> Add Windows Form...
  3. Set the name to Employees and click Add
  4. Design the form as follows:

    Lambda Square Apartments - Employees  

    Control (Name) Text Other Properties
    ListView List View   lvwEmployees View: Details
    FullRowSelect: True
    GridLines: True
    Columns
    (Name) Text TextAlign Width
    colEmployeeNumber Empl #   45
    colIFirstName First Name   65
    colLastName Last Name   65
    colTitle Title   120
    Button Button btnNewStoreItem New Employee...  
    Button Button btnClose Close  
  5. In the Solution Explorer, right-click Form1.cs and click Rename
  6. Change the name to LambdaSquareApartments and press Enter twice
  7. Design the form as follows:

    Lambda Square Apartments

    Control Name Text
    Button Button btnRegistrations Registrations ...
    Button Button btnPayments Payments ...
    Button Button btnApartments Apartments ...
    Button Button btnEmployees Employees ...
    Button Button Close btnClose
  8. Double-click the Employees button and implement the event as follows:
    private void btnEmployees_Click(object sender, EventArgs e)
    {
        Employees empls = new Employees();
        empls.Show();
    }
  9. Save all

Introduction to XML

The Extensible Markup Language, or XML, is a technique of using a document, such as a text file, to describe information and make that information available to whatever and whoever can take advantage of it. The description is done so the document can be created by one person or company and used by another person or another company without having to know who first created the document. This is because the document thus created is not a program, it is not an Topic Applied: it is just a text-based document.

Because XML is very flexible, it can be used in regular Windows applications, in databases, in web-based systems (Internet), in communication applications, in computer networks, in scientific applications, etc. To make sure that XML can be universally used without one person or group owning it, it is standardized by the W3C (http://www.w3c.org) organization. XML is released through an XML Recommendation document with a version.

In our lessons, we will learn or use XML through the .NET Framework classes. The particularity is that these classes are highly structured to take care of all facets of XML without compromising the standards. In fact, the .NET Framework classes are highly conform to the W3C standards in all areas.

To create an application that uses XML files, you have various options. You can start from a Console application, an ASP.NET application, or a Windows Forms Application. In our series of lessons, we will use Windows Forms Applications. After starting the application, at one time, you must add or use an XML document.

To create an XML file, in the document, you type units of code using normal characters of the English language.

The XML document is made of units called entities. These entities are spread on various lines of the document as you judge them necessary and as we will learn. XML has strict rules as to how the contents of the document should or must be structured.

After an XML document has been created and is available, in order to use it, you need a program that can read, analyze, and interpret it. This program is called a parser. The most popular parser used in Microsoft Windows applications is MSXML, published by Microsoft.

Markup

A markup is an instruction that defines XML. The fundamental formula of a markup is:

<tag>

The left angle bracket "<" and the right angle bracket ">" are required. Inside of these symbols, you type a word or a group of words of your choice, using regular characters of the English alphabet and sometimes non-readable characters such as ?, !, or [. The combination of a left angle bracket "<", the right angle bracket ">", and what is inside of these symbols is called a markup. There are various types of markups we will learn.

The Document Type Declaration (DTD)

As mentioned above, XML is released as a version. Because there can be various versions, the first line that can be processed in an XML file must specify the version of XML you are using. At the time of this writing, the widely supported version of the .NET Framework is 1.0. When creating an XML file, you should (should in 1.0 but must in 1.1) specify what version your file is conform with, especially if you are using a version higher than 1.0. For this reason, an XML file should start (again, must, in 1.1), in the top section, with a line known as an XML declaration. It starts with <?xml version=, followed by the version you are using, assigned as a string, and followed by ?>. An example of such a line is:

<?xml version="1.0"?>

By default, an XML file created using Microsoft Visual Studio specifies the version as 1.0. Under the XML declaration line, you can then create the necessary tags of the XML file.

Encoding Declaration

As mentioned already, the tags are created using characters of the alphabet and conform to the ISO standard. This is known as the encoding declaration. For example, most of the characters used in the US English language are known as ASCII. These characters use a combination of 7 bits to create a symbol (because the computer can only recognize 8 bits, the last bit is left for other uses). Such an encoding is specified as UTF-8. There are other standards such as UTF-16 (for wide, 2-Byte, characters).

To specify the encoding you are using, type encoding followed by the encoding scheme you are using, which must be assigned as a string. The encoding is specified in the first line. Here is an example:

<?xml version="1.0" encoding="utf-8"?>

Creating an XML File

Due to the high level of support of XML in the .NET Framework, there are various ways you can create and use an XML file. The most common technique consists of using a simple text editor. In Microsoft Windows, this would be Notepad. An XML file is first of all a normal text-based document that has a .xml extension. Therefore, however you create it, it must specify that extension.

Many other applications allow creating an XML file or generating one from an existing file. There are also commercial editors you can get or purchase to create an XML file.

Practical LearningPractical Learning: Starting an XML Document

  1. On the main menu, click PROJECT -> Add New Item...
  2. To create an XML file, in the middle list, click XML File
  3. Change the Name to Employees

    Add New Item

  4. Click Add

Writing XML Code

Introduction to the Document Object Model

To implement XML, the .NET Framework provides the System.Xml namespace. When you create an XML file, there are standard rules you should (must) follow in order to have a valid document. The standards for an XML file are defined by the W3C Document Object Model (DOM). To support these standards, the System.Xml namespace provides the XmlDocument class:This class allows you to create an XML document, to populate it with the desired contents, and to perform many other related operations on the contents of the file.

Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;

public class Exercise : System.Windows.Forms.Form
{
    Button btnDocument;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnDocument = new Button();
        btnDocument.Text = "Write";
        btnDocument.Location = new Point(12, 12);
        btnDocument.Click += new EventHandler(btnDocumentClick);

        Text = "XML Programming";
        StartPosition = FormStartPosition.CenterScreen;
        Controls.Add(btnDocument);
    }

    void btnDocumentClick(object sender, EventArgs e)
    {
        XmlDocument docMusicCollection = new XmlDocument();
    }
}

public class Program
{
    static int Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

Practical LearningPractical Learning: Introducing the Document Object Model

  1. Display th Employees form and double-click an unoccupied area of its body
  2. Change the document as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;
    
    namespace LambdaSquareApartments2
    {
        public partial class Employees : Form
        {
            public Employees()
            {
                InitializeComponent();
            }
    
            void ShowEmployees()
            {
                XmlDocument xdEmployees = new XmlDocument();
            }
    
            private void Employees_Load(object sender, EventArgs e)
            {
                ShowEmployees();
            }
        }
    }
  3. To create a new dialog box, on the main menu, click PROJECT -> Add Windows Form...
  4. Set the name to EmployeeEditor and click Add
  5. Design the form as follows:

    Lambda Square Apartments - New Employee

    Control (Name) Text Other Properties
    Label Label   Employee #:  
    TextBox Text Box txtEmployeeNumber   Modifiers: Public
    Label Label   First Name:  
    TextBox Text Box txtFirstName   Modifiers: Public
    Label Label   Last Name:  
    TextBox Text Box txtLastName   Modifiers: Public
    Label Label   Title:  
    TextBox Text Box txtTitle   Modifiers: Public
    Button Button &OK btnOK DialogResult: OK
    Button Button &Cancel btnCancel DialogResult: Cancel

    Form Property Value
    FormBorderStyle FixedDialog
    StartPosition CenterScreen
    AcceptButton btnOK
    CancelButton btnCancel
    MaximizeBox False
    MinimizeBox False
    ShowInTaskbar False
  6. Display the Employees form and double-click the New Employee button
  7. Implement the event as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;
    using System.IO;
    
    namespace LambdaSquareApartments2
    {
        public partial class Employees : Form
        {
            public Employees()
            {
                InitializeComponent();
            }
    
            void ShowEmployees()
            {
                XmlDocument xdEmployees = new XmlDocument();
            }
    
            private void Employees_Load(object sender, EventArgs e)
            {
                ShowEmployees();
            }
    
            private void btnNewEmployee_Click(object sender, EventArgs e)
            {            
                string strFileName = "../../Employees.xml";
                EmployeeEditor editor = new EmployeeEditor();
    
                if (editor.ShowDialog() == DialogResult.OK)
                {                
                    XmlDocument docEmployee = new XmlDocument();
    
                    if (!File.Exists(strFileName))
                    {
                    }
    
                    ShowEmployees();
                }
            }
        }
    }

Writing XML Code Using XmlDocument

To create XML code using XmlDocument, the class has a method called LoadXml(). Its syntax is:

public virtual void LoadXml(string xml);

This method takes a string as argument. The XmlDocument.LoadXml() method doesn't create an XML file, it only allows you to provide or create XML code. The code can be created as argument. You can also first declare and initialize a string variable with the XML code, then pass it as argument to the XmlDocument.LoadXml() method.

Practical LearningPractical Learning: Loading XML Code

  1. Change the Click event of the New Employee button as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Xml;
    
    namespace LambdaSquareApartments2
    {
        public partial class Employees : Form
        {
            public Employees()
            {
                InitializeComponent();
            }
    
            void ShowEmployees()
            {
                XmlDocument xdEmployees = new XmlDocument();
            }
    
            private void Employees_Load(object sender, EventArgs e)
            {
                ShowEmployees();
            }
    
            private void btnNewEmployee_Click(object sender, EventArgs e)
            {
                string strFileName = "../../Employees.xml";
                EmployeeEditor editor = new EmployeeEditor();
    
                if (editor.ShowDialog() == DialogResult.OK)
                {
                    XmlDocument xdEmployee = new XmlDocument();
    
                    // Find out if the file exists already
                    // If it doesn't, then create it
                    if (!File.Exists(strFileName))
                    {
                        xdEmployee.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                           "<Employees></Employees>");
                    }
    
                    ShowEmployees();
                }
            }
        }
    }
  2. Save the file

Writing XML Code Using the Code Editor

In the next sections, we will see how to create an XML file. After creating the file and displaying it in the Code Editor, you can start editing it. The Code Editor is equipped to assist you with various options. Whenever you start typing, the editor would display one or more options to you:

XML Code

When different options are presented to you, you can press the arrow keys to select an option and press Enter. You can also use the mouse to click an option. When typing other XML items, the Code Editor is equipped to work in concert with you.

Saving an XML File

Introduction

Probably the most common way to create an XML file in Microsoft Windows consists of using Notepad or any other text editor. After opening the text editor, you can enter the necessary lines of code. After creating the file, you must save it. When saving it, you can include the name of the file in double-quotes. You can also first set the Save As Type combo box to All Files and then enter the name of the file with the .xml extension.

To assist you with creating XML Files, Microsoft Visual C# includes an XML File option in the Add New Item dialog box. After selecting this option, you can accept the suggested name of the file or replace it in the Name text box. If you don't specify the extension, the wizard would add it for you.

Saving a DOM Object

If you call the XmlDocument.LoadXml() method, only the XML code is created, not the file. To actually create the Windows file, you can call the XmlDocument.Save() method. This method is provided in four versions. One of the versions takes as argument a string value. The syntax of this method is:

public virtual void Save(string filename);

The argument must be a valid filename and must include the .xml extension. If you pass a string without backlashes, the file would be created in the same folder as the current project. If you want the file to be created somewhere else (in a different directory), pass the whole path.

Practical LearningPractical Learning: Saving an XML File

  1. Change the Click event of the New Employeee button as follows:
    private void btnNewEmployee_Click(object sender, EventArgs e)
    {
        string strFileName = "../../Employees.xml";
        EmployeeEditor editor = new EmployeeEditor();
    
        if (editor.ShowDialog() == DialogResult.OK)
        {
            XmlDocument xdEmployee = new XmlDocument();
    
            if (!File.Exists(strFileName))
            {
                xdEmployee.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                   "<Employees></Employees>");
                        
                xdEmployee.Save(strFileName);
            }
    
            ShowEmployees();
        }
    }
  2. Save all

Opening an XML File

Introduction

Whether you created an XML file or someone else did, you can open it easily to view its contents. The easiest way to open an XML file is to use a text editor, such as Notepad. Because the Code Editor has a friendlier appearance and it is available to you, it is a better candidate. To open an XML file, on the main menu, you can click FILE -> Open File..., locate the file, and click Open.

After creating an XML file, one way you can use it is to display it in a grid-based window such as a spreadsheet.

An XML File in a Browser

Another way you can display an XML file is in a browser. To do this, if you see the file in Windows Explorer or in My Documents, you can double-click it. Here is an example:

Preview

Visually Opening an XML File

As mentioned already, you can start XML from an ASP.NET application. After creating the aaplication, to iindicate that it will support XML, in the Standard section of the Toolbox, drag the Xml button and drop it on a webform. To indicate what XML file the control will use, in the Properties window, use the Document Source field to specify the name or path of the file, or to select the file.

Programmatically Opening an XML File Using the DOM

At times, you will need to programmatically access an XML file. To support this operation, the XmlDocument class provides the Load() method which is available in various versions. One of the syntaxes used by this method is:

public virtual void Load(string filename);

This version takes as argument the name or path of the file. Here is an example of calling it:

private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docMusicCollection = new XmlDocument();

    docMusicCollection.Load("music.xml");
}

In this case, the compiler would look for the file in the (Release) folder of the current application. You can also provide a complete path to the file. Either way, if the compiler doesn't find the file, it would throw a FileNotFoundException exception. For this reason, it is cautious to first check that the file exists before opening it. This can be done as follows:

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
using System.IO;

public class Exercise : System.Windows.Forms.Form
{
    Button btnDocument;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnDocument = new Button();
        btnDocument.Text = "Write";
        btnDocument.Location = new Point(12, 12);
        btnDocument.Click += new EventHandler(btnDocumentClick);

        Text = "XML Programming";
        StartPosition = FormStartPosition.CenterScreen;
        Controls.Add(btnDocument);
    }

    void btnDocumentClick(object sender, EventArgs e)
    {
        XmlDocument docMusicCollection = new XmlDocument();

        string strFilename = "music.xml";

        if (File.Exists(strFilename))
            docMusicCollection.Load(strFilename);
        else
            MessageBox.Show("The file " + strFilename + " was not found",
                            "Music Collection",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

public class Program
{
    static int Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

An alternative is to handle the exception yourself.

You can also use a Stream-based object to identify the file. Once the object is ready, you can use the following version of the Load() method to open it:

public virtual void Load(Stream inStream);

This method expects a Stream type of object, such as a FileStream variable. Here is an example of calling it:

private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docMusicCollection = new XmlDocument();
    string strFilename = "music.xml";
    FileStream fstMusic = null;

    if (File.Exists(strFilename))
    {
        fstMusic = new FileStream(strFilename,
                                  FileMode.Open,
                                  FileAccess.Read);
        docMusicCollection.Load(fstMusic);
    }
    else
        MessageBox.Show("The file " + strFilename + " was not found",
                        "Music Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Practical LearningPractical Learning: Opening an XML File

  1. Change the document as follows:
    void ShowEmployees()
    {
        XmlDocument xdEmployees = new XmlDocument();
        string strFileName = "../../Employees.xml";
    
        if (File.Exists(strFileName))
        {
            xdEmployees.Load(strFileName);
        }
    }
    
    private void Employees_Load(object sender, EventArgs e)
    {
        ShowEmployees();
    }
    
    private void btnNewEmployee_Click(object sender, EventArgs e)
    {
        string strFileName = "../../Employees.xml";
        EmployeeEditor editor = new EmployeeEditor();
    
        if (editor.ShowDialog() == DialogResult.OK)
        {
            XmlDocument xdEmployee = new XmlDocument();
    
            if (!File.Exists(strFileName))
            {
                xdEmployee.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                   "<Employees></Employees>");
                        
                xdEmployee.Save(strFileName);
            }
    
            // At this time, we have an Employees.xml file. Open it
            xdEmployee.Load(strFileName);
    
            ShowEmployees();
        }
    }

Programmatically Reading an XML File

Many of the XML files you encounter will have been created by someone else. Still, because it is primarily a text document, you are expected to be able to read any XML file and figure out its content, or at least most of it. As mentioned already, you can open an XML file using a text editor such as Notepad. After opening the file, you can start by checking the document declaration, then move to other items.

Another way you can explore an XML file consists of programmatically reading it. This is also referred to as parsing (the parser parses the document). To support reading an XML file, the .NET Framework provides the abstract XmlReader class as the ancestor of classes that can read an XML file. One of the classes derived from XmlReader is called XmlTextReader. The XmlTextReader class provides the ability to read the file from the left to the right sides and from the top to the bottom sections. This class has very important characteristics you must remember:

To programmatically read an XML file, you can start by declaring a variable of type XmlTextReader using one of its constructors, including the default. To specify the file you want to open and read, you can use the constructor whose syntax is the following :

public XmlTextReader(string url);

When using this method, pass the name of the file or its path as argument. Here is an example:

private void btnDocumentClick(object sender, EventArgs e)
{
    XmlDocument docMusicCollection = new XmlDocument();
    string strFilename = "music.xml";

    if (File.Exists(strFilename))
    {
        XmlTextReader rdrXml = new XmlTextReader(strFilename);
    }
    else
        MessageBox.Show("The file " + strFilename + " was not found",
                        "Music Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

You can also identify a file using a Stream-based object. Once the object is ready, you can pass it to the following constructor of the class:

public XmlTextReader(Stream input);

Here is an example:

private void btnDocumentClick(object sender, EventArgs e)
{
    string strFilename = "music.xml";
    using( FileStream fstMusic = new FileStream(strFilename,
                                         FileMode.Open,
                                         FileAccess.Read);
    {
        if (File.Exists(strFilename))
        {
            XmlTextReader rdrMusic = new XmlTextReader(fstMusic);
        }
        else
            MessageBox.Show("The file " + strFilename + " was not found",
                            "Music Collection",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

To actually read the file, the XmlTextReader is equipped with the Read() method whose syntax is:

public override bool Read();

As you may suspect, this method only tells you that it successfully read an item. It doesn't tell you what it read. As stated already, the XmlTextReader scans a file in a left-right-top-down approach. When it has read something, it returns true. If it didn't or couldn't read something, it returns false. Therefore, you can call it to read an item. If it succeeds, it returns true. After reading that item, you can call it again to move to the next item. If there is a next item, it reads it and returns true. But, if there is no next item, the Read() method would not be able to read it and it would return false. In other words, you can ask the Read() method to continuously read the items as long as it returns true. Once it cannot read an item, you can ask it to stop. To perform this exercise, you can use either a while or a do...while loop. This would be done as follows:

private void btnDocumentClick(object sender, EventArgs e)
{
    string strFilename = "music.xml";
    FileStream fstMusic = new FileStream(strFilename,
                                         FileMode.Open,
                                         FileAccess.Read);
    if (File.Exists(strFilename))
    {
        XmlTextReader rdrMusic = new XmlTextReader(fstMusic);

        do
        {
            // Read an item and return true
            // Continue reading as long as ...
        } while (rdrMusic.Read() == true); // ... as long as Read() returns true
        // Once Read() returns false, STOP!!!

        fstMusic.Close();
    }
    else
        MessageBox.Show("The file " + strFilename + " was not found",
                        "Music Collection",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
}

To identify what was read, the XmlTextReader provides methods appropriate for the different types of item that an XML file can contain. Starting in the next lesson, we will review the types of items of a file.

XML Well-Formed

Tag Creation

Earlier, we mentioned that XML worked through markups. A simple markup is made of a tag created between the left angle bracket "<" and the right angle bracket ">". Just creating a markup is not particularly significant. You must give it meaning. To do this, you can type a number, a date, or a string on the right side of the right angle bracket ">" symbol. The text on the right side of ">" is referred to as the item's text. It is also called a value.

After specifying the value of the markup, you must close it: this is a rule not enforced in HTML but must be respected in XML to make it "well-formed". To close a tag, use the same formula of creating a tag with the left angle bracke "<", the tag, and the right angle bracket ">" except that, between < and the tag, you must type a forward slash. The formula to use is:

<tag>some value</tag>

The item on the left side of the "some value" string, in this case <tag>, is called the opening or start-tag. The item on the right side of the "some value" string, in this case </tag>, is called the closing or end-tag. Like<tag> is a markup, </tag> also is called a markup.

With XML, you create your own tags with custom names. This means that a typical XML file is made of various items. Here is an example:

<title>The Distinguished Gentleman</title>
	<director>Jonathan Lynn</director><length>112 Minutes</length>

Tag Names

When creating your tags, there are various rules you must observe with regards to their names. Unlike HTML, XML is very restrictive with its rules. For example, unlike HTML but like C/C++/C#, XML is case-sensitive. This means that CASE, Case, and case are three different words. Therefore, from now on, you must pay close attention to what you write inside of the < and the > delimiters.

Besides case sensitivity, there are some rules you must observe when naming the tags of your markups:

In our lessons, here are the rules we will apply:

In future sections, we will learn that, with some markups, you can include non-readable characters between the angle brackets. In fact, you will need to pay close attention to the symbols you type in a markup. We will also see how some characters have special meaning.

The Root

Every XML document must have one particular tag that, either is the only tag in the file, or acts as the parent of all the other tags of the same document. This tag is called the root. Here is an example of a file that has only one tag:

<rectangle>A rectangle is a shape with 4 sides and 4 straight angles</rectangle>

This would produce:

XML in a Browser

If there are more than one tag in the XML file, one of them must serve as the parent or root. Otherwise, you would receive an error. Based on this rule, the following XML code is not valid:

<rectangle>A rectangle is a shape with 4 sides and 4 straight angles</rectangle>
<square>A square is a rectangle whose 4 sides are equal</square>

This would produce:

An ill-formed XML file in a Browser

 To correct this type of error, you can change one of the existing tags to act as the root. In the following example, the <rectangle> tag acts as the parent:

<rectangle>A rectangle is a shape with 4 sides and 4 straight angles
<square>A square is a rectangle whose 4 sides are equal</square></rectangle>

This would produce:

Good Nested Tags

Alternatively, you can create a tag that acts as the parent for the other tags. In the following example, the <geometry> tag acts as the parent of the <rectangle> and of the <square> tags:

<geometry><rectangle>A rectangle is a shape with 4 sides and 4 straight angles
</rectangle><square>A square is a rectangle whose 4 sides are equal</square></geometry>

This would produce:

Preview

As mentioned already, a good XML file should have a Document Type Declaration:

<?xml version="1.0" encoding="utf-8"?><geometry><rectangle>A rectangle 
is a shape with 4 sides and 4 straight angles</rectangle><square>A 
square is a rectangle whose 4 sides are equal</square></geometry>

To give you access to the root of an XML file, the XmlDocument class is equipped with the DocumentElement property.

The Structure of an XML Tag

 

Empty Tags

We mentioned that, unlike HTML, every XML tag must be closed. We also saw that the value of a tag was specified on the right side of the right angle bracket of the start tag. In some cases, you will create a tag that doesn't have a value or, may be for some reason, you don't provide a value to it. Here is an example:

<dinner></dinner>

This type of tag is called an empty tag. Since there is no value in it, you may not need to provide an end tag but it still must be closed. Although this writing is allowed, an alternative is to close the start tag itself. To do this, between the tag name and the right angle bracket, type an empty space followed by a forward slash. Based on this, the above line can be written as follows:

<dinner />

Both produce the same result or accomplish the same role.

White Spaces

In the above example, we typed various items on the same line. If you are creating a long XML document, although creating various items on the same line is acceptable, this technique can make it (very) difficult to read. One way you can solve this problem is to separate tags with empty spaces. Here is an example:

<title>The Distinguished Gentleman</title> 
	<director>Jonathan Lynn</director>
		<length>112 Minutes</length>

Yet a better solution consists of typing each item on its own line. This would make the document easier to read. Here is an example:

<title>The Distinguished Gentleman</title>
<director>Jonathan Lynn</director>
<length>112 Minutes</length>

All these are possible and acceptable because the XML parser doesn't consider the empty spaces or end of line. Therefore, to make your code easier to read, you can use empty spaces, carriage-return-line-feed combinations, or tabs inserted in various sections. All these are referred to as white spaces.

Nesting Tags

Most XML files contain more than one tag. We saw that a tag must have a starting point and a tag must be closed. One tag can be included in another tag: this is referred to as nesting. A tag that is created inside of another tag is said to be nested. A tag that contains another tag is said to be nesting. Consider the following example:

<Smile>Please smile to the camera</Smile>
<English>Welcome to our XML Class</English>
<French>Bienvenue à notre Classe XML</French>

In this example, you may want the English tag to be nested in the Smile tag. To nest one tag inside of another, you must type the nested tag before the end-tag of the nesting tag. For example, if you want to nest the English tag in the Smile tag, you must type the whole English tag before the </Smile> end tag. Here is an example:

<Smile>Please smile to the camera<English>Welcome to our XML Class</English></Smile>

To make this code easier to read, you can use white spaces as follows:

<smile>Please smile to the camera
<English>Welcome to our XML Class</English>
</smile>

When a tag is nested, it must also be closed before its nesting tag is closed. Based on this rule, the following code is not valid:

<Smile>Please smile to the camera
<English>Welcome to our XML Class
</Smile>
</English>

The rule broken here is that the English tag that is nested in the the Smile tag is not closed inside the Smile tag but outside.

Once you have decided on the structure of your XML file, we saw that you can create it in memory using the XmlDocument.LoadXml() method. For example, the following XML code:

<?xml version="1.0" encoding="utf-8"?>
<musiccollection>
    <album>
	<shelfnumber>FJ-7264</shelfnumber>
	<title>Symphony-Bantu</title>
	<artist>Vincent Nguini</artist>
	<copyrightyear>1994</copyrightyear>
	<publisher>Mesa Records</publisher>
    </album>
    <album>
	<shelfnumber>MR-2947</shelfnumber>
	<title>None</title>
	<artist>Debbie Gibson</artist>
	<copyrightyear>1990</copyrightyear>
	<publisher>Atlantic</publisher>
    </album>
</musiccollection>

can be created in memory as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace MusicCollection
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnDocumentClick(object sender, EventArgs e)
        {
            XmlDocument docMusic = new XmlDocument();
            
            docMusic.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                             "<musiccollection><album>" +
                             "<shelfnumber>FJ-7264</shelfnumber>" +
                             "<title>Symphony-Bantu</title>" +
                             "<artist>Vincent Nguini</artist>" +
                             "<copyrightyear>1994</copyrightyear>" +
                             "<publisher>Mesa Records</publisher></album>" +
                             "<album><shelfnumber>MR-2947</shelfnumber>" +
                             "<title>None</title><artist>Debbie Gibson</artist>" +
                             "<copyrightyear>1990</copyrightyear>" +
                             "<publisher>Atlantic</publisher>" +
                             "</album></musiccollection>");
    }
}

Notice that the whole XML code can be created as one line of text and the code would be valid.

An XML Node

Introduction to XML Nodes

Consider the following example of an XML file named Videos.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Videos>
    <Video>
	<Title>The Distinguished Gentleman</Title>
	<Director>Jonathan Lynn</Director>
	<Length>112 Minutes</Length>
	<Format>DVD</Format>
	<Rating>R</Rating>
    </Video>
    <Video>
	<Title>Her Alibi</Title>
	<Director>Bruce Beresford</Director>
	<Length>94 Mins</Length>
	<Format>DVD</Format>
	<Rating>PG-13</Rating>
    </Video>
    <Video>
	<Title>Chalte Chalte</Title>
	<Director>Aziz Mirza</Director>
	<Length>145 Mins</Length>
	<Format>DVD</Format>
	<Rating>N/R</Rating>
    </Video>
</Videos>

An XML file appears as an upside-down tree: it has a root (in this case <Videos>), it can have branches (in this case <Video>), and it can have leaves (an example in this case is <Title>). As we have seen so far, all of these objects are created using the same technique: a tag with a name (such as <Title>) and an optional value. Based on their similarities, each of these objects is called a node.

To support nodes of an XML file, the .NET Framework provides the XmlNode class:

public abstract class XmlNode : ICloneable, 
				IEnumerable,
			        IXPathNavigable

The XmlNode class is the ancestor to all types of nodes. XmlNode is an abstract class without a constructor. Based on this, to get a node, you must have an object that would produce one and you can only retrieve a node from an (existing) object.

Practical LearningPractical Learning: Creating an XML Document

  1. Access the Employees.xml tab and change the document as follows:
    <?xml version="1.0" encoding="utf-8" ?>
    <Employees>
      <Employee>
        <EmployeeNumber>40685</EmployeeNumber>
        <FirstName>Justine</FirstName>
        <LastName>Sandt</LastName>
        <Title>Rent Manager</Title>
      </Employee>
      <Employee>
        <EmployeeNumber>73048</EmployeeNumber>
        <FirstName>Raymond</FirstName>
        <LastName>Wilkinson</LastName>
        <Title/>
      </Employee>
      <Employee>
        <EmployeeNumber>60949</EmployeeNumber>
        <FirstName>Mark</FirstName>
        <LastName>Reason</LastName>
        <Title>Maintenance Technician</Title>
      </Employee>
    </Employees>
  2. Save all

Introduction to Node Types

To make XML as complete and as efficient as possible, it can contain various types of nodes. The categories or possible types of nodes are identified by an enumeration named XmlNodeType. If you use an XmlTextReader object to scan a file, when calling Read(), the class has a property named NodeType that allows you to identify the node that was read. NodeType is a read-only property of type XmlNodeType and it is declared as follows:

public override XmlNodeType NodeType { get; }

Therefore, when calling the XmlTextReader.Read() method, you can continuously check the value of the XmlTextReader.NodeType property to find out what type of node was just read, and then you can take an appropriate action.

         

Home Copyright © 2005-2020, FunctionX Next