|
Reading a RSS feed with the C# XmlReaderPosted on 01. Feb, 2010 by Wim Haanstra in C#, Coding. |
Today I needed to parse a LARGE (1.9GB) XML file and extract some information from it. Loading it in a XmlDocument (my favorite .NET way of handling XML) wasn’t really a possibility, because that would cause Out of Memory errors the minute I would try it.
I am using a XmlReader for this and I noticed that there arent really many usable examples on the internet about this, so here is just a small example I created to show how you could read a RSS feed.
Sample after the break…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // File to open up, can be an URL too string XmlFileUrl = @"c:\feed.xml"; using (XmlReader reader = new XmlTextReader(XmlFileUrl)) { // Initialize a list for storage of the items List<rssItem> items = new List<rssItem>(); // boolean to see if a node was opened before bool openItem = false; RssItem item = new RssItem(); // Loop the reader, till it cant read anymore while (reader.Read()) { // An object with the type Element was found. if (reader.NodeType == XmlNodeType.Element) { // Check name of the node and write the contents in the object accordingly. if (reader.Name == "item") { item = new RssItem(); openItem = true; } else if (reader.Name == "title" && openItem) item.title = reader.ReadElementContentAsString(); else if (reader.Name == "link" && openItem) item.link = reader.ReadElementContentAsString(); else if (reader.Name == "description" && openItem) item.description = reader.ReadElementContentAsString(); } // EndElement was found, check if it is named item, if it is, store the object in the list and set openItem to false. else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "item" && openItem) { openItem = false; items.Add(item); } } } |
The RssItem class I created is just a simple class containing a couple of properties:
1 2 3 4 5 6 7 | public class RssItem { public string title { get; set; } public string pubDate { get; set; } public string link { get; set; } public string description { get; set; } } |




