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

2
  • 1
    possible duplicate of What is a NullReferenceException and how do I fix it? Commented Mar 19, 2015 at 17:12
  • You should check whether oldNode is not null before accessing its innertext. if(oldNode != null) oldNode.InnerText = pstrValueToWrite; Commented Mar 19, 2015 at 17:15

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

"//" will fetch settings node from anywhere in the file, that may not be desirable. Also @ph94 hasn't expressed any requirement to do so.
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 - You are right, updated my answer. It didnt need the extra /, the provided example updates the database tag (provided that was desired)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.