Classe C# per parsing Atom da Blogspot e da PhpBB
25 May 2010
Nessun commento
Di seguito una semplice classe con due metodi per leggere (o come dicono gli americani, consumare) atom feed.
In entrambi i casi i due metodi ricevono in input l’URL del feed da parsare e ne restituiscono un Dictionary composito (semplicemente perchè mi serviva un tipo di dato di questo tipo).
In teoria sarebbe stato sufficiente l’utilizzo del solo metodo GetAtomItemsBlog() per leggere anche altri Atom, sfortunatamente però il tipo di Atom che esporta PhpBB non viene correttamente letto da questo metodo. Per ovviare al problema ho creato un secondo metodo GetAtomItemsForum() che utilizza la classe SyndicationFeed al posto di Atom10FeedFormatter.
Resta comunque interessante il primo metodo visto che va ad utilizzare la sintassi Linq.
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | public class AtomRssReader { public Dictionary<string , Dictionary<string, string>> GetAtomItemsBlog(string MyUrl) { XmlReader reader = XmlReader.Create(MyUrl); Atom10FeedFormatter atom = new Atom10FeedFormatter(); Dictionary</string><string , Dictionary<string, string>> Ret = new Dictionary</string><string , Dictionary<string, string>>(); Dictionary</string><string , string> Temp; if (atom.CanRead(reader)) { atom.ReadFrom(reader); var items = from item in atom.Feed.Items.OfType<syndicationitem>() select new { Id = item.Id, Title = item.Title.Text, Url = item.Links.Last<syndicationlink>().Uri.AbsoluteUri, Published = item.PublishDate, Updated = item.LastUpdatedTime, Subtitle = item.Summary.Text }; foreach (var item in items) { Temp = new Dictionary<string , string>(); Temp.Add("Title", item.Title); Temp.Add("Url", item.Url); Temp.Add("Published", Convert.ToString(item.Published.LocalDateTime)); Temp.Add("Updated", Convert.ToString(item.Updated.LocalDateTime)); Temp.Add("Subtitle", item.Subtitle); Ret.Add(item.Id, Temp); } } reader.Close(); return Ret;; } public Dictionary</string><string , Dictionary<string, string>> GetAtomItemsForum(string MyUrl) { Dictionary</string><string , Dictionary<string, string>> Ret = new Dictionary</string><string , Dictionary<string, string>>(); XmlReader reader = XmlReader.Create(MyUrl); SyndicationFeed feed = SyndicationFeed.Load(reader); Dictionary</string><string , string> Temp; foreach (var item in feed.Items) { Temp = new Dictionary</string><string , string>(); Temp.Add("Title", item.Title.Text); Temp.Add("Published", Convert.ToString(item.LastUpdatedTime.LocalDateTime)); Temp.Add("Updated", Convert.ToString(item.LastUpdatedTime.LocalDateTime)); Temp.Add("Url", item.Id); Temp.Add("Subtitle", ((TextSyndicationContent)item.Content).Text); Ret.Add(item.Id, Temp); } return Ret; ; } } |