Home

Saving and Opening an XML File

 

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:

Save As

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.

Practical Learning Practical Learning: Saving an XML File

  1. To save the file, on the main menu, click File -> Save XMLFile1.xml As...
  2. Access the main folder of the current project and, inside of it, open a sub-folder of the same name (it should be opened already). In the sub-folder of the same name, open the bin sub-folder followed by the Debug sub-folder
  3. Change the name of the file to students
     
    Save As
  4. Click Save

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.

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

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 btnDocument_Click(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.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

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

        private void btnDocument_Click(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");
        }
    }
}

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 btnDocument_Click(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");
}

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:

private void btnDocument_Click(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");
}

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 btnDocument_Click(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);
    }
    else
        MessageBox.Show("The file " + strFilename + " was not found");
}

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 btnDocument_Click(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");
}

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 © 2007-2013, FunctionX Next