C#xmlAttribute.Value对象引用未设置为对象的实例
本文关键字:对象 实例 设置 Value 对象引用 C#xmlAttribute | 更新日期: 2023-09-27 18:29:34
早上好。
很快。
使用XmlDocument我正在以编程方式创建文档,该文档需要如下所示(示例):
<report>
<header version="1" reportDate="2013-08-27" salesDate="2013-08-26"/>
<data>
<companies>
<company id="ABCD">
<customers>
<customer id="100000" storeId="AA"/>
<customer id="100001" storeId="AB"/>
<customer id="100002" storeId="AC"/>
</customers>
</company>
</companies>
</data>
</report>
我需要从一些DataGridView中获取数据,因此foreach循环正在大量使用。
这就是为什么下面显示的代码让我感到困惑:
对象引用未设置为对象的实例
这是我使用的代码示例:
[...]
XmlNode customersNode = doc.CreateElement("customers");
companyNode.AppendChild(customersNode);
XmlNode customerNode;
XmlAttribute customerAttribute;
foreach (DataGridViewRow row in dgvCustomers.Rows)
{
customerNode = doc.CreateElement("customer");
customerAttribute = doc.CreateAttribute("id");
customerAttribute.Value = row.Cells[0].Value.ToString();
//
// __HERE__ is the problem (or a line above)
//
customerNode.Attributes.Append(customerAttribute);
customerAttribute = doc.CreateAttribute("storeId");
customerAttribute.Value = row.Cells[1].Value.ToString();
customerNode.Attributes.Append(customerAttribute);
customersNode.AppendChild(customerNode);
}
[...and so on...]
还有
customerNode.Attributes.Append(customerAttribute);
下划线(VS2010编辑器)与此提示:
Possible 'System.NullReferenceException'
但我认为这是上述问题的原因?
感谢您的支持,并提前感谢您的时间和知识分享
致以最良好的问候!
我还没有尝试运行显示的代码,但是:您可能会发现简化它会使出错变得更加困难:
XmlElement customerNode; // <==== note this is XmlElement, not XmlNode
XmlAttribute customerAttribute;
foreach (DataGridViewRow row in dgvCustomers.Rows)
{
customerNode = doc.CreateElement("customer");
customerNode.SetAttribute("id", row.Cells[0].Value.ToString());
customerNode.SetAttribute("storeId", row.Cells[1].Value.ToString());
customersNode.AppendChild(customerNode);
}
您可能还想检查问题是否实际上不是row.Cells[0].Value.ToString()
或row.Cells[1].Value.ToString()
正在引发异常。