分析XML
这是使用RSS feed最难的部分。我们必须使用刚才创建的XmlDocument来得到含有我们自己数据的XML结点。我们普遍感兴趣的结点是:
·Feed的标题,它存放在feed XML中的/rss/channel/title文件里面
·Feed的文章,它存放在feed XML中的/rss/channel/item文件里面。在这个位置可能有多个结点。
·文章的标题,它存放在文章结点中的title里面。
·文章的描述,它存放在文章结点的description里面。
·文章的链接,它存放在文章结点的link里面。
我们可以使用XmlDocument对象内置的SelectSingleNode函数和SelectNodes函数来得到这些结点。这两个函数都可以接受XPath查询,也都可以返回与查询结果相匹配的一个或多个结点。
Listing D这段代码告诉我们如何使用XmlDocument和Xpath从RSS feed中分析出每个单独的元素。
Listing D
//Get an XmlDocument object that contains the feed's XML
XmlDocument feedDocument =
GetXmlDocumentFromFeed("http://rss-feeds.msn.com/autos/autosnews.xml");
//Create a XmlNamespaceManager for our namespace.
XmlNamespaceManager manager =
newXmlNamespaceManager(feedDocument.NameTable);
//Add the RSS namespace to the manager.
manager.AddNamespace("rss", "http://purl.org/rss/1.0/");
//Get the title node out of the RSS document
XmlNode titleNode =
feedDocument.SelectSingleNode("/rss/channel/title", manager);
//Get the article nodes
XmlNodeList articleNodes =
feedDocument.SelectNodes("/rss/channel/item", manager);
//Loop through the articles and extract
// their data.
foreach (XmlNode articleNode in articleNodes)
{
//Get the article's title.
string title =
articleNode.SelectSingleNode("title", manager).InnerText;
//Get the article's link
string link =
articleNode.SelectSingleNode("link", manager).InnerText;
//Get the article's description
string description =
articleNode.SelectSingleNode("description", manager).InnerText;
}
//Get an XmlDocument object that contains the feed's XML
XmlDocument feedDocument =
GetXmlDocumentFromFeed("http://rss-feeds.msn.com/autos/autosnews.xml");
//Create a XmlNamespaceManager for our namespace.
XmlNamespaceManager manager =
newXmlNamespaceManager(feedDocument.NameTable);
//Add the RSS namespace to the manager.
manager.AddNamespace("rss", "http://purl.org/rss/1.0/");
//Get the title node out of the RSS document
XmlNode titleNode =
feedDocument.SelectSingleNode("/rss/channel/title", manager);
//Get the article nodes
XmlNodeList articleNodes =
feedDocument.SelectNodes("/rss/channel/item", manager);
//Loop through the articles and extract
// their data.
foreach (XmlNode articleNode in articleNodes)
{
//Get the article's title.
string title =
articleNode.SelectSingleNode("title", manager).InnerText;
//Get the article's link
string link =
articleNode.SelectSingleNode("link", manager).InnerText;
//Get the article's description
string description =
articleNode.SelectSingleNode("description", manager).InnerText;
}
不是所有的RSS feed的创建都是相同的
如果所有的RSS feed都使用相同的格式,它将变得更强大,然而RSS feed有许多不同的版本和实现。在这篇文章中描述的格式适合大部分的feed,可能有少部分的RSS feed格式与这个格式不同。