Reputation: 26538
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
Upvotes: 1
Views: 2443
Reputation: 28764
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");
Upvotes: 2
Reputation: 73351
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");
Upvotes: 6
Reputation: 6958
You should add the "PlayerCodes" elemnt to you XDocument first.
Upvotes: 0