我正在尝试更新XML文档中的3个数据,但是获取“对象引用未设置为对象的实例”错误。这是我想要更新的XML文件格式:
<?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>
这是抛出错误的C#代码:
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);
}
}
有人能看到问题吗?我对更新XML不太熟悉,所以这里可能存在一些基本错误。
答案 0 :(得分:1)
我已在本地对其进行了调试,正如Pawel建议的那样,您需要对命名空间进行一些更改:
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);
}
}
希望这有帮助。