Click here to Skip to main content
Click here to Skip to main content
Go to top

Storing and Retrieving Settings from XML

, 10 Nov 2008
Rate this:
Please Sign up or sign in to vote.
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

License

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

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 4 Pinmembersivanphani17-Jun-11 16:51 
GeneralComment on Article PinmemberArchElf24-Nov-08 23:06 
GeneralRe: Comment on Article PinmemberArchElf24-Nov-08 23:09 
GeneralSettings & Resources PinmemberPat Tormey17-Nov-08 1:31 
GeneralThank´s! PinmemberDon Mattéo11-Nov-08 11:54 
GeneralRe: Thank´s! PinmemberAhsanS11-Nov-08 20:43 
GeneralNice Effort PinmemberMuhammad Shahid Farooq11-Nov-08 0:44 
GeneralRe: Nice Effort PinmemberAhsanS11-Nov-08 3:48 
QuestionHave you tried this? Pinmemberhughd11-Nov-08 0:24 
AnswerRe: Have you tried this? PinmemberAhsanS11-Nov-08 3:47 
GeneralRe: Have you tried this? PinmemberAdeel Hussain11-Nov-08 9:11 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 10 Nov 2008
Article Copyright 2008 by AhsanS
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid