-2

When I run this code I have the error "object reference not set to an instance of an object" thrown and I have no idea why.

I have used debug to break the code on some points and I notice that it causes the error after it passes on the foreach for the child comment.

I'm glad if someone can shine some light on this problem

My Xml:

<?xml version=\"1.0\" encoding=\"utf - 8\"?>
<data type=\"array\" success=\"1\" status=\"200\">
<item>
    <id>1</id>
    <comment>aaa</comment>
    <author>john</author>
    <children/>
</item>
<item>
    <id>2</id>
    <comment>bbb</comment>
    <author>paul</author>
    <children>
        <item>
            <id>3</id>
            <comment>ccc</comment>
            <author>lisa</author>
            <children/>
        </item>
    </children>
</item>

My Code:

 XDocument document = XDocument.Parse(xml);
 foreach (XElement item in document.Root.Elements("item"))
      {
           post.comments.Add(new Comment(item));
      }

My Class:

 public class Comment
{
    public string id { get; set; }
    public string comment { get; set; }
    public string author { get; set; }
    public IList<Comment> children { get; set; }

    public Comment(XElement elem)
    {
        id = elem.Element("id").Value.ToString();
        comment = elem.Element("comment").Value.ToString();
        author = elem.Element("author").Value.ToString();

        foreach (XElement childComment in elem.Element("children").Elements())
        {
            children.Add(new Comment(childComment));
        }

    }
}
Adrews
  • 1
  • 5
  • 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) – Preston Guillot Feb 26 '16 at 19:01

1 Answers1

0

Your constructor for Comment assumes that public IList<Comment> children has been initialized but there's no code that's actually creating the list.

If you have access to System.Linq this is easiest:

children = elem.Element("children").Elements().Select(el => new Comment(el)).ToList();

If you cannot include using System.Linq, you may simply initialize the children member before your loop:

children = new List<Comment>();
foreach (XElement childComment in elem.Element("children").Elements())
{
    children.Add(new Comment(childComment));
}
clarkitect
  • 1,720
  • 14
  • 23