简体   繁体   中英

How can I import a raw RSS feed in C#?

Does anyone know an easy way to import a raw, XML RSS feed into C#? Am looking for an easy way to get the XML as a string so I can parse it with a Regex.

Thanks, -Greg

This should be enough to get you going...

using System.Net 

WebClient wc = new WebClient();

Stream st = wc.OpenRead(“http://example.com/feed.rss”);

using (StreamReader sr = new StreamReader(st)) {
   string rss = sr.ReadToEnd();
}

If you're on .NET 3.5 you now got built-in support for syndication feeds (RSS and ATOM). Check out this MSDN Magazine Article for a good introduction .

If you really want to parse the string using regex (and parsing XML is not what regex was intended for), the easiest way to get the content is to use the WebClient class.It got a download string which is straight forward to use. Just give it the URL of your feed. Check this link for an example of how to use it .

I would load the feed into an XmlDocument and use XPATH instead of regex, like so:

XmlDocument doc = new XmlDocument();

HttpWebRequest request = WebRequest.Create(feedUrl) as HttpWebRequest;

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    StreamReader reader = new StreamReader(response.GetResponseStream());
    doc.Load(reader);

    <parse with XPATH>
}

What are you trying to accomplish?

I found the System.ServiceModel.Syndication classes very helpful when working with feeds.

The RSS is just xml and can be streamed to disk easily. Go with Darrel's example - it's all you'll need.

XmlDocument (located in System.Xml, you will need to add a reference to the dll if it isn't added for you) is what you would use for getting the xml into C#. At that point, just call the InnerXml property which gives the inner Xml in string format then parse with the Regex.

You might want to have a look at this: http://www.codeproject.com/KB/cs/rssframework.aspx

The best way to grab an RSS feed as the requested string would be to use the System.Net.HttpWebRequest class. Once you've set up the HttpWebRequest's parameters (URL, etc.), call the HttpWebRequest.GetResponse() method. From there, you can get a Stream with WebResponse.GetResponseStream(). Then, you can wrap that stream in a System.IO.StreamReader, and call the StreamReader.ReadToEnd(). Voila.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM