Click here to Skip to main content
15,881,881 members
Articles / Desktop Programming / Windows Forms
Article

Storing and Retrieving Settings from XML

Rate me:
Please Sign up or sign in to vote.
4.06/5 (10 votes)
10 Nov 2008CPOL3 min read 65.2K   45   11
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:

XML
<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:

C#
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.

C#
#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.

C#
/// <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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) F3 Technologies
Pakistan Pakistan
I have been working in Microsoft Technologies for the past 13 years. I have experience in working with both desktop and web applications. i like helping others in solving there problems.

Comments and Discussions

 
GeneralMy vote of 4 Pin
sivanphani17-Jun-11 16:51
sivanphani17-Jun-11 16:51 
GeneralComment on Article Pin
ArchElf24-Nov-08 23:06
ArchElf24-Nov-08 23:06 
GeneralRe: Comment on Article Pin
ArchElf24-Nov-08 23:09
ArchElf24-Nov-08 23:09 
GeneralSettings & Resources Pin
Pat Tormey17-Nov-08 1:31
Pat Tormey17-Nov-08 1:31 
GeneralThank´s! Pin
Don Mattéo11-Nov-08 11:54
Don Mattéo11-Nov-08 11:54 
GeneralRe: Thank´s! Pin
AhsanS11-Nov-08 20:43
AhsanS11-Nov-08 20:43 
GeneralNice Effort Pin
Muhammad Shahid Farooq11-Nov-08 0:44
professionalMuhammad Shahid Farooq11-Nov-08 0:44 
GeneralRe: Nice Effort Pin
AhsanS11-Nov-08 3:48
AhsanS11-Nov-08 3:48 
QuestionHave you tried this? Pin
hughd11-Nov-08 0:24
hughd11-Nov-08 0:24 
AnswerRe: Have you tried this? Pin
AhsanS11-Nov-08 3:47
AhsanS11-Nov-08 3:47 
GeneralRe: Have you tried this? Pin
Adeel Hussain11-Nov-08 9:11
Adeel Hussain11-Nov-08 9:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.