1

I have an aspx page that accepts 3 user inputs called

  1. Name
  2. Date
  3. Description

I want to create an xml document using these. When I try to append the child, I get a NullReferenceException with a detail of

{"Object reference not set to an instance of an object."}

Here is my code

            string name = EventName.Text;
            string date = DatePicker.SelectedDate.ToString();
            string description = NewsDescription.Text;

            //Create XML Document
            XmlDocument doc = new XmlDocument();

            //Event Name
            XmlElement elem = doc.CreateElement("Name");
            XmlText text = doc.CreateTextNode(name.ToString());
            doc.DocumentElement.AppendChild(elem);
            doc.DocumentElement.AppendChild(text);

            //Event Date
            XmlElement elem2 = doc.CreateElement("Date");
            XmlText text2 = doc.CreateTextNode(date.ToString());
            doc.DocumentElement.AppendChild(elem2);
            doc.DocumentElement.AppendChild(text2);

            //Event Description
            XmlElement elem3 = doc.CreateElement("Description");
            XmlText text3 = doc.CreateTextNode(description.ToString());
            doc.DocumentElement.AppendChild(elem3);
            doc.DocumentElement.AppendChild(text3);

            doc.Save(Console.Out);

Visual Studio Screen shot

Mike Debela
  • 1,930
  • 3
  • 18
  • 32
onTheInternet
  • 6,421
  • 10
  • 41
  • 74
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Panagiotis Kanavos May 24 '16 at 15:47
  • The error is pretty obvious. Just check the objects involved to see which one is null. – Panagiotis Kanavos May 24 '16 at 15:48
  • Possible duplicate of [DocumentElement.AppendChild throws object reference not set to an instance of an object](http://stackoverflow.com/questions/16276229/documentelement-appendchild-throws-object-reference-not-set-to-an-instance-of-an) – abrown May 24 '16 at 15:52
  • Exactly the same issue faced in this question: http://stackoverflow.com/questions/16276229/documentelement-appendchild-throws-object-reference-not-set-to-an-instance-of-an – abrown May 24 '16 at 15:53

1 Answers1

0

doc has no Element yet.

XmlElement elem = doc.CreateElement("Name"); // is just declaration

So,

doc.DocumentElement.AppendChild(elem);

Should be:

doc.AppendChild(elem);
Mike Debela
  • 1,930
  • 3
  • 18
  • 32