DocumentElement.AppendChild throws object reference not set to an instance of an object

只愿长相守 提交于 2020-01-15 20:57:11

问题


I'm trying to create a new xml file, write data into it and than save.

Here is the code:

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");

the line doc.DocumentElement.AppendChild(rootnode); is the line that throws the

"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.

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

Any help is much appreciated.


回答1:


You haven't document element yet, because the only child you've been added is a declaration. Replace

doc.DocumentElement.AppendChild(rootnode);

with:

doc.AppendChild(rootnode);


来源:https://stackoverflow.com/questions/16276229/documentelement-appendchild-throws-object-reference-not-set-to-an-instance-of-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!