For awhile now, I have been wanting to write up how to use XML RSS Feed fetching, parsing and output but I came across this website/article and I think it does just as good as I would to describe HOWTO get and use a RSS Feed.
So, go check it out at: XML Deserialization.
With that being said, I have copied some of the content from the site for you to see a bit more of the simplicity that is being involved in the code provided from that site and no, not everyone uses the methods on the website, not even I but maybe in the future I will try it…
Start by going in to your Mainpage.xaml.cs and find then type the following:
WebClient downloader = new WebClient();
Uri rssUri = new Uri(“http://rss.cnn.com/rss/edition.rss”, UriKind.Absolute);
//This code was not written by Lance Seidman…
Now, if you were trying to get the users input, you could also do:
var XMLFEED = txtFeedURI.Text;
This would allow the user to input his/her desired RSS Feed URL. Now if this was what you wanted, you would update the rssUri code as follows:
Uri rssUri = new Uri(XMLFEED, UriKind.Absolute);
You might be asking, well if I allow the user to input the URL to a feed, how will I know the elements/items to output? Well, if it doesn’t really matter, you can actually use a MessageBox and XML Read + Parse to remove the XML look and plainly show the contents without knowing the RSS Fields.
How would you do something like this? Well, off the top of my head, you’d need to include System.IO and System.Xml.Linq and in the OpenReadCompleted function have something like:
XDocument doc = XDocument.Load(Stream);
* Note, you should do something like: using (Stream s = e.Result).
So, in the end you should have something similar to this:
using (Stream s = e.Result)
XDocument doc = XDocument.Load(s);
/* Optionally you could apply the content to a MessageBox (See A.)
OR put it in a Textbox (See B.)
txtXML.Text = doc; //Or depending on what else you may do, add .ToString();
However, if you want, you should remove the duplicates that may occur and to do that you can do doc.ToString(SaveOptions.OmitDuplicateNamespaces);
Yes, this means you’d need to do: MessageBox.Show(doc.ToString(SaveOptions.OmitDuplicateNamespaces);
PLEASE REMEMBER TO ALWAYS HAVE ERROR CONTROL! THIS IS VERY HELPFUL AND CREATE UNIQUE ERROR CODES SO THAT PEOPLE CAN REPORT THEM TO YOU AND YOU KNOW WHERE/WHY IT OCCURRED!
Well, I just wanted to point out a minor thing you could do differently but I won’t even begin to touch this topic any further, unless you guys want to see how I do it, which is different but this seems to be just as efficient.
Have a good day (morning or afternoon) or night (evening).