DocumentElement.AppendChild抛出未设置为对象实例的对象引用 [英] DocumentElement.AppendChild throws object reference not set to an instance of an object
问题描述
我试图创建一个新的xml文件,将数据写入并保存。
I'm trying to create a new xml file, write data into it and than save.
这里是代码:
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);
是抛出
对象引用未设置为对象实例的行
"object reference not set to an instance of an object"
我一直在互联网上,但我似乎找不到一个答案为什么这个错误被抛出。
I've been looking on internet but I don't seem to find an answer to why this error is being thrown.
当我检查rootnode时,我看到它的innerHTML完全填充了我的xml,所以似乎是正确的。我没有看到任何空对象,但也许我错过了一些东西。
When I check the rootnode I see it's innerHTML completely filled with my xml so that seems to be correct. I don't see any null-objects but maybe I'm missing something
任何帮助是非常赞赏。
推荐答案
你还没有文档元素,因为你添加的唯一的孩子是一个声明。替换
You haven't document element yet, because the only child you've been added is a declaration. Replace
doc.DocumentElement.AppendChild(rootnode);
其中:
doc.AppendChild(rootnode);
这篇关于DocumentElement.AppendChild抛出未设置为对象实例的对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!