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.