我正在尝试创建一个新的 xml 文件,将数据写入其中然后保存。
代码如下:
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"
我一直在互联网上查找,但我似乎没有找到引发此错误的原因的答案。
当我检查根节点时,我看到它的 innerHTML 完全充满了我的 xml,所以这看起来是正确的。我没有看到任何空对象,但也许我遗漏了什么
非常感谢任何帮助。
请您参考如下方法:
您还没有文档元素,因为您添加的唯一子元素是声明。替换
doc.DocumentElement.AppendChild(rootnode);
与:
doc.AppendChild(rootnode);
