DocumentElement.AppendChild throws object referenc

2019-08-09 19:35发布

问题:

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