对象引用未设置为具有XDocument的对象的实例

pri*_*kar 1 c# linq-to-xml

这段代码有什么问题

XDocument xDocument = new XDocument();

for (int i = 0; i < 5; i++)

{

xDocument.Element("PlayerCodes").Add(

new XElement("PlayerCode", i.ToString())

);

}

xDocument.Save(@"c:\test.xml");
Run Code Online (Sandbox Code Playgroud)

我收到错误"对象引用未设置为对象的实例."

基本上我想创建xml文件.它不存在

请帮忙

Dav*_*rab 6

文档中没有任何内容,因此XDocument.Element("PlayerCodes")显示为null.

首先加载文档.

或者这样做

XDocument xDocument = new XDocument();

for (int i = 0; i < 5; i++)        
{
  if( XDocument.Element("PlayerCodes") == null)
  {
    XDocument.Add(new XElement("PlayerCodes"));
  }

  xDocument.Element("PlayerCodes").Add(new XElement("PlayerCode", i.ToString()));

}

xDocument.Save(@"c:\test.xml");
Run Code Online (Sandbox Code Playgroud)