Csharp/CSharp Tutorial/XML/RSS

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Process RSS

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
class MainClass
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        Stream rssFeedStream = client.OpenRead("http://yourRssFeedURL");
        XmlReader reader = XmlReader.Create(rssFeedStream);
        reader.MoveToContent();
        while (reader.ReadToFollowing("item"))
        {
            ProcessItem(reader.ReadSubtree());
        }
    }
    static void ProcessItem(XmlReader reader)
    {
        reader.ReadToFollowing("title");
        string title = reader.ReadElementContentAsString("title", reader.NamespaceURI);
        reader.ReadToFollowing("link");
        string link = reader.ReadElementContentAsString("link", reader.NamespaceURI);
        Console.WriteLine("{0}\n\t{1}", title, link);
    }
}

Select nodes in RSS

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
class MainClass
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        string rssFeed = client.DownloadString("http://blogs.apress.ru/wp-rss2.php");
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(rssFeed);
        XmlNodeList nodes = doc.SelectNodes("rss/channel/item/title");
        foreach (XmlNode node in nodes)
        {
            Console.WriteLine(node.InnerText);
        }
    }
}