0

I need to parse this xml document (portion only):

<channel>
 <item>
   <title>a</title>
   <description>aa</description>
   <link url= "www.a.com" />
 </item>
<item>
   <title>b</title>
   <description>bb</description>
   <link url= "www.b.com" />
 </item>
<item>
   <title>c</title>
   <description>cc</description>
   <link url= "www.c.com" />
 </item>
<item>
   <title>d</title>
   <description>dd</description>
    <channelContents>
      <item>
         <title>a</title>
         <description>aa</description>
         <link url= "www.a.com" />
      </item>
      <item>
         <title>b</title>
         <description>bb</description>
         <link url= "www.b.com" />
      </item>
      <item>
         <title>c</title>
         <description>cc</description>
         <link url= "www.c.com" />
      </item>
    </channelContents>
 </item>
</channel>

This is my code:

List<ItemList> itemList = null;
reader = XmlReader.Create(new StringReader(content));
loadedData = XDocument.Load(reader);
var query = from i in loadedData.Descendants("item")
    select new ItemList
    {
        Title = (string)i.Element("title"),
        Description = (string)i.Element("description"),
        Link = (string)i.Element("link").Attribute("url").Value
    };
itemList = query.ToList();

I'm getting an error whenever I parse the Link. And I think I found out why, it is because of the tag <channelContents>. The item with title "d" has that tag which was present after the description in which, violated the pattern of the <item>. Is it possible to just parse the items in <channelContents> since it has the same item(a, b and c)?

I'm getting an error:

NullReferenceException because itemList is null.

I tried removing Link = (string)i.Element("link").Attribute("url").Value and it did work. But I need to get the Link.

casperOne
  • 73,706
  • 19
  • 184
  • 253

1 Answers1

0

Your problem is that the fourth item doesn't have a immediate link node.

  var query = from i in loadedData.Descendants("item")
                        select new 
                        {
                            Title = (string)i.Element("title"),
                            Description = (string)i.Element("description"),
                            Link = (string)i.Descendants("link").FirstOrDefault().Attribute("url").Value
                        };

might do what you want.. return 7 nodes.. a,b,c,d and again another a,b,c

parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85