el *_*rty 2 c# xml xmldocument c#-4.0
我正在尝试创建一个新的 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");
Run Code Online (Sandbox Code Playgroud)
该行doc.DocumentElement.AppendChild(rootnode);是抛出
“你调用的对象是空的”
我一直在寻找互联网,但我似乎没有找到为什么会抛出这个错误的答案。
当我检查 rootnode 时,我看到它的 innerHTML 完全充满了我的 xml,所以这似乎是正确的。我没有看到任何空对象,但也许我遗漏了一些东西
任何帮助深表感谢。
您还没有记录元素,因为您添加的唯一子元素是声明。代替
doc.DocumentElement.AppendChild(rootnode);
Run Code Online (Sandbox Code Playgroud)
和:
doc.AppendChild(rootnode);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4545 次 |
| 最近记录: |