2013-04-29 79 views
1

我試圖創建一個新的xml文件,將數據寫入它並保存。DocumentElement.AppendChild拋出未設置爲對象實例的對象引用

下面是代碼:

XmlDocument doc= new XmlDocument(); 
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null); 
doc.AppendChild(dec); 

XmlElement rootnode = doc.CreateElement("Root"); 

foreach (var item in list) 
{ 
    XmlElement parent = ordersNIA.CreateElement("ParentElement"); 

    XmlElement childOne = ordersNIA.CreateElement("childOne"); 
    childOne.InnerText = "This is the first child"; 
    parent.AppendChild(childOne); 

    XmlElement childTwo = ordersNIA.CreateElement("childTwo"); 
    childOne.InnerText = "This is the second child"; 
    parent.AppendChild(childTwo); 

    XmlElement childThree = ordersNIA.CreateElement("childThree"); 
    childOne.InnerText = "This is the third child"; 
    parent.AppendChild(childThree); 

    rootnode.AppendChild(parent); 

} 

doc.DocumentElement.AppendChild(rootnode); 
doc.Save("xmlDocument.xml"); 

doc.DocumentElement.AppendChild(rootnode);是拋出

我的

「未設置爲一個對象的實例對象引用」 的路線我一直在尋找互聯網,但我似乎沒有找到答案,爲什麼這個錯誤被拋出。

當我檢查根節點時,我發現它的innerHTML完全填充了我的xml,所以這似乎是正確的。我沒有看到任何空對象,但也許我失去了一些東西

任何幫助,非常感謝。

回答

3

您還沒有文檔元素,因爲您添加的唯一孩子是一個聲明。更換

doc.DocumentElement.AppendChild(rootnode); 

有:

doc.AppendChild(rootnode); 
+0

我只是想出了同樣的事情,感謝您的快速回復強硬:) – 2013-04-29 10:40:20

相關問題