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