0

When I execute the code, I've a problem on the foreach. When it executes the 'foreach' for the first time, it goes to the 'catch' by saying 'Object reference not set to an object instance'

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

The RSS feed is structures like this :

<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>

Do you have a solution ?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user2274060
  • 896
  • 5
  • 18
  • 35

1 Answers1

2

You are using xDoc instead of x when you creating anonymous types.And accessing Value property is throwing the exception because xDoc doesn't have a link element.Change your query like this:

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")
             });
Selman Genç
  • 100,147
  • 13
  • 119
  • 184