【问题标题】:XDocument - Object reference is not defined to an object instance [duplicate]XDocument - 对象引用未定义到对象实例[重复]
【发布时间】:2014-05-13 19:25:15
【问题描述】:

当我执行代码时,我在 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>

你有解决办法吗?

【问题讨论】:

    标签: c# .net nullreferenceexception


    【解决方案1】:

    当您创建匿名类型时,您使用的是 xDoc 而不是 x。访问 Value 属性会引发异常,因为 xDoc 没有链接元素。像这样更改您的查询:

    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")
                 });
    

    【讨论】:

    • 谢谢。有用。我的错误非常愚蠢
    猜你喜欢
    • 2010-09-12
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2013-11-17
    • 1970-01-01
    相关资源
    最近更新 更多