0

I am trying to write something to xml file. I have a function:

bool WriteValueTOXML(string pstrValueToRead, string pstrValueToWrite)
    {
        try
        {
            XmlTextReader reader = new XmlTextReader("config.ini");
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();
            XmlNode oldNode;
            XmlElement root = doc.DocumentElement;
            oldNode = root.SelectSingleNode(@"/settings/" + pstrValueToRead);
            oldNode.InnerText = pstrValueToWrite;
            doc.Save("config.ini");
            return true;
        }
        catch (NullReferenceException e)
        {
            MessageBox.Show(e.Message);
            return false;
        }
    }

When I am trying to set InnerText in oldNode (oldNode.InnerText = pstrValueToWrite;) the NullReferenceException is thrown with message "Object reference not set to an instance of an object".

File that I am trying to write to is here:config.ini

ph94
  • 27
  • 2
  • 5
  • 1
    possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Izzy Mar 19 '15 at 17:12
  • You should check whether oldNode is not null before accessing its innertext. if(oldNode != null) oldNode.InnerText = pstrValueToWrite; – nobody Mar 19 '15 at 17:15

2 Answers2

2

oldNode = root.SelectSingleNode(@"/settings/" + pstrValueToRead); must be returning null. Put a break point just after that line of code and check if that's the case. If so, adjust your xpath so it returns an actual node.

rory.ap
  • 34,009
  • 10
  • 83
  • 174
0

This example works with the below assumptions:

XmlDocument doc = new XmlDocument();
using(XmlTextReader reader = new XmlTextReader(@"C:\Temp\config.ini"))
{
   doc.Load(reader);
}
XmlElement root = doc.DocumentElement;
XmlNode oldNode = root.SelectSingleNode(@"/settings/database");
oldNode.InnerText = "Blah Blah2";
doc.Save(@"C:\Temp\config.ini.out");

This is assuming you want to update the inner text your path to database of the database tag to something else.

SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
  • "//" will fetch `settings` node from anywhere in the file, that may not be desirable. Also @ph94 hasn't expressed any requirement to do so. – Ravi M Patel Mar 19 '15 at 17:26
  • I didn't give you down vote. Well, the oldNode is still null. Maybe the file is formatted wrong? On the other hand read function works good. – ph94 Mar 19 '15 at 17:27
  • @ph94 - You are right, updated my answer. It didnt need the extra `/`, the provided example updates the database tag (provided that was desired) – SwDevMan81 Mar 19 '15 at 17:29