Return List Item Collection from XML Feed in C#

Freshness Warning
This post is more than 2 years old. Please bear in mind its age when reading.

This example shows how to return a list of items from a feed as a C# collection.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;

 

namespace FeedInfo
{
 public class FeedItem {
  public string Item1{ get; set; }
  public string Item2{ get; set; }
 }

 public class Feed
 {
  public static List<FeedItem> GetFeedInfo()
  {
   XmlReaderSettings xrs = new XmlReaderSettings();
   xrs.XmlResolver = new XmlUrlResolver();
   xrs.ValidationType = ValidationType.DTD;
   xrs.ProhibitDtd = false;

   try
   {
    using (XmlReader xtr = XmlTextReader.Create("http://feed.url", xrs))
    {
     XDocument xd = XDocument.Load(xtr);

     return (from incident in xd.Descendants("tpeg_message")
         select new FeedItem
         {
          Item1 = (string)incident.Element("Item1"),
          Item2 = (string)incident.Element("Item2").Attribute("Sub_Attribute"),
                 }).ToList();

     xtr.Close();
    }
   }
   catch (WebException ex)
   {
    return new List<FeedItem>();
   }
  }
 }
}
 

I'm running the 39th BMW Berlin Marathon on 30th September 2012 for the British Lung Foundation, who are currently funding research on the prevention of lung damage in COPD and many other areas related to lung disease.

I'm participating with my sister Claire Kewney and, on behalf of the charity, would appreciate even the smallest donation. My own JustGiving page is here, our team page is here.

if you're in the UK, you can also donate using your mobile phone by texting NKEW82 £5 (or any amount) to 70070. Your donation will be appreciated!

Comments

Your Comment
Your Name
E-mail Address (This won't be published)
Website URL

You can manage your Kewney.com account by logging in. [ Log On ]