Home

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.

An XML File in a Browser

After creating an XML file, one way you can use it is to display it in a grid-based window such as a spreadsheet. 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:

 

Using a Style Sheet to Display an XML File in a Browser

When an XML file is displayed in a browser, it appears in a format that could be unclear. If you want the XML code to display as if it were HTML, you can create a cascading style sheet that would format the tags and display the text as you prefer. Here is an example: 

employee.css
EmplNumber
{
	display: block;
	font-weight: bold;
	font-size: 16pt;
	color: white;
	font-family: Garamond, Georgia, 'Times New Roman' , Serif;
	background-color: #990000;
}
FirstName
{
	font-size: 10pt;
	font-family: Verdana, Tahoma, Arial, Sans-Serif;
	background-color: white;
}
LastName
{
	font-size: 10pt;
	font-family: Verdana, Tahoma, Arial, Sans-Serif;
	background-color: white;
}
HourlySalary
{
	font-size: 10pt;
	color: #ff0066;
	font-family: Verdana, Tahoma, Arial, Sans-Serif;
	background-color: white;
	display: block;
}

Then, in the first line of the XML file, you can add a line such as the following:

<?xml:stylesheet href="employee.css" type="text/css" ?>  

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:

using System;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load("Videos.xml");

            return 0;
        }
    }
}

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.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            string strFilename = "Videos123.xml";

            if (File.Exists(strFilename))
                xmlDoc.Load(strFilename);
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

            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:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename  = "Videos.xml";
            XmlDocument xmlDoc  = new XmlDocument();
            FileStream fsVideos = null;

            if (File.Exists(strFilename))
            {
                fsVideos = new FileStream(strFilename,
                                                 FileMode.Open,
                                                 FileAccess.Read);

                xmlDoc.Load(fsVideos);
            }
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

            return 0;
        }
    }
}
 

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:

  • This class proceeds with a forward only approach: it reads a character or a word, moves to the next, and cannot refer back. This means that, after it has visited an item and has moved ahead, you cannot use it to refer to an item back
  • This class is read-only: you cannot use it to edit or modify an item (but, when you get to an item, you can use another object to modify the item)

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:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";

            if (File.Exists(strFilename))
                XmlTextReader rdrXml = new XmlTextReader(strFilename);
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

            Console.WriteLine();
            return 0;
        }
    }
}

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:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            FileStream fsVideos = new FileStream(strFilename,
                                                 FileMode.Open,
                                                 FileAccess.Read);

            if (File.Exists(strFilename))
                XmlTextReader rdrXml = new XmlTextReader(fsVideos );
            else
                Console.WriteLine("The file {0} could not be located",
                                  strFilename);

            fsVideos.Close();
            Console.WriteLine();
            return 0;
        }
    }
}

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:

using System;
using System.IO;
using System.Xml;

namespace VideoCollection1
{
    class Program
    {
        static int Main(string[] args)
        {
            string strFilename = "Videos.xml";
            FileStream fsVideos = new FileStream(strFilename,
                                                 FileMode.Open,
                                                 FileAccess.Read);

            XmlTextReader rdrXml = new XmlTextReader(fsVideos );

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

            fsVideos.Close();
            Console.WriteLine();
            return 0;
        }
    }
}

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.

 

Previous Copyright © 2006-2016, FunctionX, Inc. Next