我有以下代码LINQ查询返回空结果
nodes = data.Descendants(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Results")).Nodes();
System.Collections.Generic.IEnumerable<Result> res = new List<Result>();
if (nodes.Count() > 0)
{
var results = from uris in nodes
select new Result
{
URL =
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Url")).Value,
Title =
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Title")).Value,
Description =
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}Description")).Value,
DateTime =
((XElement)uris).Element(XName.Get("{http://schemas.microsoft.com/LiveSearch/2008/04/XML/web}DateTime")).Value,
};
res = results;
}
如果结果是谁拥有这些URL一个对象,标题,描述和日期时间变量的定义。
这一切都正常工作,但是当节点中的'节点'不包含描述元素(或至少我认为多数民众赞成什么投掷它)程序命中“res =结果;” 一行代码并抛出“对象引用未设置为...”错误,并在“选择新结果”后突出显示整个部分。
如何解决此问题?
问题依然存在..也许它不是从节点丢失的元素。有没有一种方法可以用不同的方式来添加“保护措施”? – Ryan
@Ryan:尝试我的替代(更简单)的代码,如果仍然失败,请编辑一个简短的* complete *程序(包括XML)到您的问题中,以便我们可以看到发生了什么。 –
这种更好的编写代码的方式避免了这个问题..非常感谢Jon – Ryan