LINQ .ToList()在单个结果上失败

时间:2011-01-22 01:51:46

标签: c# xml linq parsing rss

可能是周五晚上的一个晚上,我想回家,或者更有可能我只是看不到问题......

我有以下的LINQ代码:

mthumbs = itm.Elements(nsr + "thumbnail") != null ? 
      (from mt in itm.Elements(nsr + "thumbnail")
       select new MediaThumbnail
       {
         mediaThumbnailUrl = (string)mt.Attribute("url") ?? null,
         mediaThumbnailHeight = (string)mt.Attribute("height") ?? null,
         mediaThumbnailWidth = (string)mt.Attribute("width") ?? null,
         mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null
        }).ToList() : null

MediaThumbnail类看起来像:

public class MediaThumbnail
{
    public string mediaThumbnailUrl { get; set; }
    public string mediaThumbnailWidth { get; set; }
    public string mediaThumbnailHeight { get; set; }
    public string mediaThumbnailTime { get; set; }
}

并驻留在MediaOptElement类中,该类看起来像:

public class MediaOptElement
{
    public string mediaPlayer { get; set; }
    public string mediaRating { get; set; }
    public string mediaRatingScheme { get; set; }
    public string mediaTitle { get; set; }
    public string mediaTitleType { get; set; }
    public string mediaDescription { get; set; }
    public string mediaDescriptionType { get; set; }
    public string mediaKeywords { get; set; }
    public List<MediaThumbnail> mthumbs { get; set; }
    public string mediaCategory { get; set; }
    public string mediaCategoryScheme { get; set; }
    public string mediaCategoryLabel { get; set; }
    public string mediaHash { get; set; }
    public string mediaHashAlgorithm { get; set; }
    public string mediaCopyRights { get; set; }
    public string mediaCopyrightsUrl { get; set; }
    public string mediaRestrictions { get; set; }
    public string mediaRestrictionsRelation { get; set; }
    public string mediaRestrictionsType { get; set; }
    public List<MediaCredit> mediaCredit { get; set; }
}

一些示例XML:

   <?xml version="1.0" encoding="UTF-8" ?> 
   <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
      <channel>
        <title>wdbj7.com - Sports</title> 
        <link>http://www.wdbj7.com/sports/?track=rss</link> 
        <description>Headlines from wdbj7.com</description> 
        <language>en</language> 
        <copyright>©2011, wdbj7.com</copyright> 
        <lastBuildDate>Fri, 21 Jan 2011 10:47:00 -0500</lastBuildDate> 
        <item>
          <title>Brookville improves to 15-0</title> 
          <link>http://www.wdbj7.com/sports/wdbj7-brookville-improves-to-150-01212011,0,675989.story?track=rss</link> 
          <description><p>The Brookville girls&apos; basketball team graduated two college basketball players last year. That was the last time they lost anything.</p> <p>The Lady Bees are 14-0 on the young season and looked to add to that mark Thursday night against Seminole district rival Liberty.</p> <p>The Minettes playing at home, had just three wins on the year.&nbsp; Haley Comer gets two for the home team. Liberty takes the 2-0 lead.&nbsp; That is when it becomes the Katie Deacon show.</p> <p>The four-year varsity player starts it with the defense.&nbsp; She gets the steal on one end and a basket on the other.</p> <p>Deacon takes her game behind the three point arc!&nbsp; That beats the buzzer at the end of the first quarter!</p> <p>Deacon still not done.&nbsp; She gets another steal and feeds George Mason signee Talisha Watts.<br /><br />Brookville improves to 15-0 with the 57-34 win. <br /><br /></p></description> 
          <pubDate>Fri, 21 Jan 2011 10:47:00 -0500</pubDate> 
          <media:thumbnail url="http://media.trb.com/media/thumbnails/story/2011-01/276990840-21074740.jpg" /> 
          <media:content url="http://media.trb.com/media/alternatethumbnails/story/2011-01/276990840-21074739.jpg" /> 
       </item>
     </channel>
  </rss>

当我运行我的代码时,我收到以下错误:

   Object reference not set to an instance of an object.

堆栈跟踪是:

   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__6e(XElement mt) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader \RssReader.cs:line 843
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.<>c__DisplayClass7d.<parseFeed>b__57(XElement itm) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 667
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at RssAggregator.Reader.RssReader.parseFeed(XDocument xmlDoc) in E:\Aggregator\VersionControl\FeedsParserLINQ\RssAggregator\Reader\RssReader.cs:line 666

我可能错了,但我认为当LINQ查询只返回单个结果时会出现问题。但是,我需要能够处理可能只有一个媒体的情况:缩略图节点或许多媒体:缩略图节点。有任何想法吗?!谢谢!

3 个答案:

答案 0 :(得分:4)

我认为问题出在这一行:

mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null

如果该属性不存在,那么当您尝试使用NullReferenceException属性时,您将获得Value。请注意,在您的示例中,time属性不存在。

试试这个:

...
using System.Linq;
using System.Xml.Linq;

var mthumbs = itm.Elements( nsr + "thumbnail" )
                 .Select( e => new MediaThumbnail
                  {
                     mediaThumbnailUrl = string.Format( "{0}", e.Attribute("url" ),
                     mediaThumbnailHeight = string.Format( "{0}",e.Attribute("height" ),
                     mediaThumbnailWidth = string.Format( "{0}",e.Attribute("width" ),
                     mediaThumbnailTime = string.Format( "{0}", e.Attribute("time" )
                  })
                 .ToList();

答案 1 :(得分:1)

我会看他的路线:

mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null

我的猜测是mt.Attribute("time")为空,这就是造成异常的原因。从我们掌握的信息中很难确定。也许是这样的事情:

mediaThumbnailTime = (mt.Attribute("time") != null ? (string)mt.Attribute("time").Value : null)

答案 2 :(得分:0)

您的问题出现在以下代码行中:

mediaThumbnailTime = (string)mt.Attribute("time").Value ?? null

请注意,它与其他3的不同之处在于您在此处使用.Value。如果元素没有属性“time”,则会失败 - 在这种情况下,.Attribute()将返回null,并且访问该属性会为您提供NullReferenceException