user2751773
user2751773

Reputation: 129

Error while creating XML file

I am trying to create a simple XML file, but I am getting the exception

Object reference not set to an instance of an object

at this part:

doc.Root.Add(persons);

What am I doing wrong?

 XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
    XElement persons = new XElement("Persons");
    XElement[] el ={new XElement("PersonInfo",new XAttribute("ID",1),
               new XElement("Name","ali"),
               new XElement("Phone","222222"))
               };

    persons.Add(el);
    doc.Add(persons);

    doc.Save("PhoneBook.xml", SaveOptions.None);
    Response.Write("ok");
}

Upvotes: 0

Views: 66

Answers (1)

Taylan Aydinli
Taylan Aydinli

Reputation: 4363

You should just use:

doc.Add(persons);

Then you will get this XML:

<Persons>
  <PersonInfo ID="1">
    <Name>ali</Name>
    <Phone>222222</Phone>
  </PersonInfo>
</Persons>

An empty XDocument has no Root. That's why you get a NullReferenceException when you try to access it.

Upvotes: 1

Related Questions