overlook77
overlook77

Reputation: 59

UPdating XML, getting "Object Reference Not Set To An Instance Of An Object"

I am trying to update 3 pieces of data in an XML document but getting an "Object Reference Not Set To An Instance Of An Object" error. This is the XML file format I am trying to update:

<?xml version="1.0" encoding="US-ASCII" standalone="true"?>
<ExportSettings xmlns="CompanyName" ExportName="Data Export" Dataset="TestName">
  <General>
     <AsOfDate>03/31/15</AsOfDate>
     <PriceDate>03/31/16</PriceDate>  
  </General>
  <Source>
      <Set>Set Name</Set>
  </Source>
</ExportSettings>

This is the C# code that is throwing the error:

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            {
                string strAsOfDate = dateTimePickerAsOfDate.Text;
                string strPriceDate = dateTimePickerPriceDate.Text;
                string strSetName = txtboxSet.Text;

                XmlDocument doc = new XmlDocument();
                doc.Load(strXMLfilepath);
                XmlNode General;
                XmlNode root = doc.DocumentElement;
                General = root.SelectSingleNode("/ExportSettings/General");
                General["AsOfDate"].InnerText = strAsOfDate;
                General["PriceDate"].InnerText = strPriceDate;
                XmlNode Source;
                Source = root.SelectSingleNode("/ExportSettings/Source");
                Source["Set"].InnerText = strSetName;
                doc.Save(strXMLfilepath);

            }
        }
        catch (System.Exception excep)
        {
            MessageBox.Show(excep.Message);
        }
    }

Can anyone see the problem? I am not very familiar with updating XML so there may be something basic wrong here.

Upvotes: 0

Views: 1594

Answers (1)

Stephen Wilson
Stephen Wilson

Reputation: 1514

I've debugged this locally and as Pawel suggests, you need to make some changes regarding namespaces:

private void btnUpdate_Click(object sender, EventArgs e)
{
    try
    {
        {
            string strAsOfDate = dateTimePickerAsOfDate.Text;
            string strPriceDate = dateTimePickerPriceDate.Text;
            string strSetName = txtboxSet.Text;

            XmlDocument doc = new XmlDocument();
            doc.Load(strXMLfilepath);

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("ab", "CompanyName");

            XmlNode General;
            XmlNode root = doc.DocumentElement;
            General = root.SelectSingleNode("//ab:General", nsmgr);
            General["AsOfDate"].InnerText = strAsOfDate;
            General["PriceDate"].InnerText = strPriceDate;

            doc.Save(strXMLfilepath);
        }
    }
    catch (System.Exception excep)
    {
        MessageBox.Show(excep.Message);
    }
}

Hope this helps.

Upvotes: 1

Related Questions