【发布时间】:2010-10-12 21:03:19
【问题描述】:
我正在从一个 XML 文件填充一个匿名对象。到现在为止,
commentary.Elements("Commentator")
总是有一个值,所以我从来不用检查空值。不过我不得不删除它,现在它在尝试读取该行时失败了。
我正在查看代码,但我不知道要更改什么,因为它被选择到匿名对象的属性中。
var genericOfflineFactsheet = new
{
Commentary = (from commentary in doc.Elements("Commentary")
select new
{
CommentaryPage = (string)commentary.Attribute("page"),
BusinessName = (string)commentary.Attribute("businessName"),
Commentator = (from commentator in commentary.Elements("Commentator")
select new CommentatorPanel // ASP.NET UserControl
{
CommentatorName = (string)commentator.Attribute("name"),
CommentatorTitle = (string)commentator.Attribute("title"),
CommentatorCompany = (string)commentator.Attribute("company")
}).FirstOrDefault()
}).FirstOrDefault()
问题是,我无法完全删除该行,因为有时commentary.Elements("Commentator") 确实 有一个值。我确定这个问题之前已经处理过,但我不知道该怎么做。有什么想法吗?
【问题讨论】:
-
当您说失败时,您是否收到 ObjRef 错误?
-
@Nix,这是一个 NullReferenceException
-
不要重温过去,但我正在再次调查,您确定您的代码没有其他问题吗?我刚刚拿走了你的东西,并通过了一个 Commentary 为空的测试,它工作正常吗?
-
不,我很确定就是这样 - 我按照您的建议应用了 where 子句并且它有效。我没有改变其他任何东西。
标签: c# linq-to-xml anonymous-types xelement