LINQ TO XML解析RSS提要 [英] LINQ TO XML Parse RSS Feed

查看:97
本文介绍了LINQ TO XML解析RSS提要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用LINQ to Xml解析RSS feed

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

这是RSS提要: 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();

为了测试代码,我在Linq查询的第一行上放置了一个断点,并在中间窗口中使用以下命令对其进行了测试:

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

我输入:

xdoc.Element(ns + "item");

以上方法工作并返回了一个对象,但我正在寻找所有物品

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

所以我输入了..

xdoc.Elements(ns + "item");

即使有超过10个项目,此操作也不返回任何内容,decendants方法也不起作用,并且还返回null.

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

有人能给我一些指向我要去哪里的指示吗?我也尝试过用rdf代替名称空间.

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.

谢谢

推荐答案

您引用的是错误的名称空间.所有元素都使用默认名称空间而不是rdf,因此您的代码应如下所示:

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

这篇关于LINQ TO XML解析RSS提要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆