tags:

views:

946

answers:

3

what is wrong with this code

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

I am getting error " Object reference not set to an instance of an object."

Basically I want to create the xml file. It is not in existence

Please help

+6  A: 

There isn't anything in the document, so XDocument.Element("PlayerCodes") comes up as null.

Load the document first.

Or do this

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");
David Basarab
Basically I want to create the xml file. It is not in existence
priyanka.sarkar
Thank you very much. It helped
priyanka.sarkar
A: 

You should add the "PlayerCodes" elemnt to you XDocument first.

Mohammadreza
+2  A: 

A more concise way to create the same document looks like this:

var doc = new XDocument(
    new XElement("PlayerCodes",
        Enumerable.Range(0, 5).Select(i => new XElement("PlayerCode", i))
    )
);

doc.Save(@"c:\test.xml");
Joel Mueller