XDocument - 对象引用未定义到对象实例

时间:2014-05-13 19:25:16

标签: c# .net nullreferenceexception

当我执行代码时,我在foreach上遇到了问题。当它第一次执行'foreach'时,它会通过说'对象引用未设置为对象实例'来进入'catch'

String u = "C:\\Users\\Lolo\\Desktop\\fluxRSS.xml";

try{
    XDocument xDoc = XDocument.Load("myfluxRSS.xml");
    var items = (from x in xDoc.Descendants("item")
                 select new
                 {
                     title = x.Element("title").Value,
                     link = xDoc.Element("link").Value,
                     pubDate = xDoc.Element("pubDate").Value,
                     description = xDoc.Element("description").Value
                 });

    if (items != null)
    {

         foreach (var i in items){
             Console.WriteLine(i);
         }
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

RSS提要是这样的结构:

<xml version="...">
<rss>
    <channel>
       <item>
           <!-- Rest of the tags -->
       </item>
       <item></item>
       <!-- Rest of the items -->
    </channel>
    <channel>
        <item>
            <!-- Rest of the tags -->
        </item>
        <!-- Rest of the items -->
    </channel>  
</rss>

你有解决方案吗?

1 个答案:

答案 0 :(得分:2)

在创建匿名类型时,您正在使用xDoc而不是x。并且访问Value属性会引发异常,因为xDoc没有link元素。请更改您的查询:

var items = (from x in xDoc.Descendants("item")
             select new
             {
                 title = (string)x.Element("title"),
                 link = (string)x.Element("link"),
                 pubDate = (string)x.Element("pubDate"),
                 description = (string)x.Element("description")
             });