ph94
ph94

Reputation: 27

C# .Net XML - Object reference not set to an instance of an object - writing value to XML

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

Upvotes: 0

Views: 1910

Answers (2)

SwDevMan81
SwDevMan81

Reputation: 49978

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.

Upvotes: 0

rory.ap
rory.ap

Reputation: 35260

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.

Upvotes: 2

Related Questions