【发布时间】:2016-06-10 03:08:58
【问题描述】:
运行此代码时出现错误 “你调用的对象是空的” 抛出,我不知道为什么。
我已经使用调试在某些点上破坏了代码,我注意到它在传递给子注释的 foreach 后会导致错误。
如果有人能解决这个问题,我很高兴
我的 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>
我的代码:
XDocument document = XDocument.Parse(xml);
foreach (XElement item in document.Root.Elements("item"))
{
post.comments.Add(new Comment(item));
}
我的班级:
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));
}
}
}
【问题讨论】: