LINQ TO XML Parse RSS Feed

▼魔方 西西 提交于 2019-12-11 20:25:49

问题


I'm trying to parse an RSS feed using LINQ to Xml

This is the rss feed: http://www.surfersvillage.com/rss/rss.xml

My code is as follows to try and parse

List<RSS> results = null;

XNamespace ns = "http://purl.org/rss/1.0/";
XNamespace rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";

XDocument xdoc = XDocument.Load("http://www.surfersvillage.com/rss/rss.xml");

results = (from feed in xdoc.Descendants(rdf + "item")
           orderby int.Parse(feed.Element("guid").Value) descending
           let desc = feed.Element("description").Value
           select new RSS
           {
               Title = feed.Element("title").Value,
               Description = desc,
               Link = feed.Element("link").Value
           }).Take(10).ToList();

To test the code I've put a breakpoint in on the first line of the Linq query and tested it in the intermediate window with the following:

xdoc.Element(ns + "channel");

This works and returns an object as expect

i type in:

xdoc.Element(ns + "item");

the above worked and returned a single object but I'm looking for all the items

so i typed in..

xdoc.Elements(ns + "item");

This return nothing even though there are over 10 items, the decendants method doesnt work either and also returned null.

Could anyone give me a few pointers to where I'm going wrong? I've tried substituting the rdf in front as well for the namespace.

Thanks


回答1:


You are referencing the wrong namespace. All the elements are using the default namespace rather than the rdf, so you code should be as follow:

List<RSS> results = null;

XNamespace ns = "http://purl.org/rss/1.0/";
XDocument xdoc = XDocument.Load("http://www.surfersvillage.com/rss/rss.xml");
results = (from feed in xdoc.Descendants(ns + "item")
           orderby int.Parse(feed.Element(ns + "guid").Value) descending
           let desc = feed.Element(ns + "description").Value
           select new RSS
           {
               Title = feed.Element(ns + "title").Value,
               Description = desc,
               Link = feed.Element(ns + "link").Value
           }).Take(10).ToList();


来源:https://stackoverflow.com/questions/5889954/linq-to-xml-parse-rss-feed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!