65.9K
CodeProject is changing. Read more.
Home

Storing and Retrieving Settings from XML

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.06/5 (10 votes)

Nov 10, 2008

CPOL

3 min read

viewsIcon

67112

An easy way of saving and restoring application settings from an XML File

Introduction

I have learned a lot from CodeProject. I feel very happy to be part of such a community and now is the time to give something back.

Today I read an article about reading data from XML using typed datasets here on The Code Project. We can do it that way, but I don't like using datasets for this purpose. So I went about writing an article on how to do it using another method.

Every application nowadays, small or big, needs things to be configurable according to the environment, e.g. path to images folder, date time format, etc. This article is specifically about one of the best practices, i.e. XML to save and retrieve settings at run time.

Background

How often have you found yourself in a position where you need to save application settings in a file??? Huh often??

And you start to think what are the options available to you? INI, database, config file or XML.

Each of them has benefits and drawbacks.

For example:

INI file is after all a text file and it is not that fast to read from a text file.

Saving settings in a database is not that feasible until and unless you have got something that is a big secret which you don't want to reveal in any case.  This is because in settings we normally save things which are required time and again. Moreover, we don't want to query the database again for getting things and when those settings get changed, we will not like to call the database again for saving.

Another option which we are left with is the XML file. It is one of the ways which is adapted quite often. But what is not good about using an XML file is the way in which we retrieve information from the XML file. There are quite a few ways to deal with an XML file.

We can load the files into a dataset and  use its method to get the values and write back. But by using that, what we often forget is that dataset is not meant for this purpose. Using dataset for such small things is not a good solution. You will achieve your target but using dataset for this purpose is very slow compared to the method I am going to mention now. 

Using the Code

Many people find it tedious to use standard XML functions provided by .NET Framework to deal with XML. I hope after going through the code below, they won't fear it much.

Firstly, I am providing a function to read a value from an XML file.

Your settings file for the following function should be something like this:

<settings>
<databasepath>your path to database</databasepath>
</settings>

Now for using the function given below, just call the method and provide the name of the node you want to read. For example:

string connectionString = ReadValueFromXML(databasepath);

What the function below will do for you is that it will create an expression and using the XpathNavigator and XPathNodeIterator  it will return the value of the node you requested.

#region Read Data From XML
/// <summary>
/// Reads the data of specified node provided in the parameter
/// </summary>
/// <param name="pstrValueToRead">Node to be read</param>
/// <returns>string containing the value</returns>
private static string ReadValueFromXML(string pstrValueToRead)
{
    try
    {
        //settingsFilePath is a string variable storing the path of the settings file 
        XPathDocument doc = new XPathDocument(settingsFilePath);
        XPathNavigator nav = doc.CreateNavigator();
        // Compile a standard XPath expression
        XPathExpression expr;
        expr = nav.Compile(@"/settings/" + pstrValueToRead);
        XPathNodeIterator iterator = nav.Select(expr);
        // Iterate on the node set
        while (iterator.MoveNext())
        {
            return iterator.Current.Value;
        }
        return string.Empty;
    }
    catch
    {
        //do some error logging here. Leaving for you to do 
        return string.Empty;
    }
}

Now that you are done with reading the values from XML file using standard XML functions, it is time to move on and write to the same settings file.

Some fellows might be thinking that reading is easy and writing is difficult, not at all guys. It is very simple too.

Just use the function below and pass in two parameters. I think that there is nothing to explain in the function below. It is well commented and extremely simple.

/// <summary>
/// Writes the updated value to XML
/// </summary>
/// <param name="pstrValueToRead">Node of XML to read</param>
/// <param name="pstrValueToWrite">Value to write to that node</param>
/// <returns></returns>
private static bool WriteValueTOXML(string pstrValueToRead, string pstrValueToWrite)
{
    try
    {
        //settingsFilePath is a string variable storing the path of the settings file 
        XmlTextReader reader = new XmlTextReader(settingsFilePath);
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        //we have loaded the XML, so it's time to close the reader.
        reader.Close();
        XmlNode oldNode;
        XmlElement root = doc.DocumentElement;
        oldNode = root.SelectSingleNode("/settings/" + pstrValueToRead);
        oldNode.InnerText = pstrValueToWrite;
        doc.Save(settingsFilePath);
        return true;
    }
    catch
    {
        //properly you need to log the exception here. But as this is just an
        //example, I am not doing that. 
        return false;
    }
}
#endregion

Points of Interest

Reading and writing XML is very simple and normally, it is considered to be the best practice to save settings in an XML file. With XPath and XPathNodeIterator available, using XML has never been such an easy task.

History

  • 10th November, 2008: Initial post