Return List Item Collection from XML Feed in C#

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>();
   }
  }
 }
}
 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.