C#xmlAttribute.Value未将对象引用设置为对象的实例

时间:2013-08-30 09:42:23

标签: c# xmldocument

早上好。

不久。

使用 XmlDocument 我是programmaticaly创建文档,需要看起来像这样(示例):

<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 循环正在大量使用。

我无法解决或找不到答案(总是关于阅读XML,没有创建)是下面显示的代码引发我的原因:

  

对象引用未设置为对象的实例

这是我使用的代码示例:

[...]

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'

但我认为这是上述问题的原因?

非常感谢您的支持,并提前感谢您的时间和知识分享。

祝你好运!

1 个答案:

答案 0 :(得分:1)

我还没有尝试过运行显示的代码,但是:你可能会发现简化它会让错误变得更难:

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()引发异常。

相关问题