Datos personales

martes, enero 06, 2009

Lector RSS en C# 3.5 y LINQ

(Este artículo tiene otro punto de vista en este otro que creo mejora este sistema: http://oscarmontesinos.blogspot.com/2009/08/lector-rss-con-framework-35-sin-linq.html)

Retomando mi actividad normal diaria, me he encontrado con una clase para leer RSS que tenía por ahí guardada y que he retocado para usar LINQ.

Primero he creado una clase con los atributos que necesito y a la que he llamado Articulo:

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

public class Articulo
{
public DateTime Fecha;
public string Titulo;
public string Contenido;
public string Enlace;
public Articulo()
{
}
public Articulo(DateTime pFecha, string pTitulo, string pContenido, string pEnlace)
{
Fecha = pFecha;
Titulo = pTitulo;
Contenido = pContenido;
Enlace = pEnlace;
}
}

Luego he creado una clase para leer las RSS y que consta de 2 métodos:
  • uno público que es el punto de entrada y dónde le pasamos una lista de cadenas que representa cada una de ellas una dirección de subscripción a una RSS
  • uno privado que es el que se encarga de ir leyendo cada servidor de noticias.
Aquí el código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
using JPA.XML.Clases.Entidades;

public class LectorRSS
{
public List CargarRSS(List feeds)
{
//Ejemplos de links
//List feeds = new List
//{
// "http://noticiasjpa.blogspot.com/feeds/posts/default",
// "http://dnnotaword.blogspot.com/feeds/posts/default",
//};
List articulos = new List();
foreach (String sFeed in feeds)
{
leerRSS(articulos,sFeed);
}
return articulos;
}
private void leerRSS(List articulos, string sFeed)
{
try
{
//cargamos el XML a leer.
var feed = XDocument.Load(sFeed);
//la consulta en LINQ:
var result = from c in feed.Root.Elements()
where c.Name.LocalName == "entry" //Selecciono sólo las entradas
select new Articulo //por cada entrada creo un objeto Artículo.
{
Fecha = c.Elements().Where(Fecha => Fecha.Name.LocalName == "published").
Select(Fecha => DateTime.Parse(Fecha.Value)).First(),
Titulo = c.Elements().Where(Titulo => Titulo.Name.LocalName == "title").
Select(Titulo => Titulo.Value).First(),
Contenido = c.Elements().Where(Contenido =>Contenido.Name.LocalName == "content").
Select(Contenido => Contenido.Value).First(),
Enlace = c.Elements().Where(Enlace => Enlace.Name.LocalName=="link").
Select(Contenido => Contenido.Attribute("href").Value).Last()
};
articulos.AddRange(result);
//A continuación tenéis el código sustituído:
//foreach (XElement xElement in ListaArticulos)
//{
// if (xElement.Name.LocalName == "entry")
// {
// Articulo articulo = new Articulo();
// foreach (XElement xElement2 in xElement.Elements())
// {
// switch (xElement2.Name.LocalName)
// {
// case "title":
// articulo.Titulo = xElement2.Value;
// break;
// case "content":
// articulo.Contenido = xElement2.Value;
// break;
// case "published":
// articulo.Fecha = DateTime.Parse(xElement2.Value);
// break;
// case "link":
// foreach (XAttribute xAttribute in xElement2.Attributes())
// {
// if (xAttribute.Name == "href")
// {
// articulo.Enlace = xAttribute.Value;
// }
// }
// break;
// }
// }
// if (articulo.Contenido.Trim() != "")
// {
// articulos.Add(articulo);
// }
// }
//}
}
catch (Exception ex)
{
throw new Excepciones.LectorRSS(ex.Message);
}
}
}

Etiquetas

.net (1) ALGORITMO (4) algoritmos (1) Android (1) angular (2) aplicaciones WEB (1) ARGENTINA (1) ASP (4) asp .NET (1) ASP .NET Identity (1) attach (1) Azure (1) base de datos (1) BINDING (1) BioInformática (2) bootstrap (1) C (2) C# (27) castellano (1) catalán (1) Charla (1) CheckedListBox (1) Clase (1) clausura transitiva (2) CLIENTES (1) Closing (1) Combobox (1) Comisiones (1) CONCURSO (1) condones (1) consultas (1) corrupta (1) CORS OWIN (1) CORS WEB API 2 (1) Criptografía (1) CUENTA NARANJA (1) Custom Control (1) Daniel Seara (1) DATAGRIDVIEW (1) David Salgado (2) dendrograma (6) depurar (1) desarrollo (1) Deserializar (1) DEVCAMP (2) durex (1) e-DNI (1) el Guille (2) Eladio Rincón (1) elGamal (1) encriptación (1) encuesta (1) Entidad (1) ERROR (2) error 3624 (1) España (1) España es nido de víboras. (1) Euclides (1) Euclides extendido (1) evento (1) eventos. (1) factorización (1) factorizar (1) física (1) Framework 2.0 (1) Framework 3.5 (5) Framework 4 (2) Francisco González (1) Francisco Ruiz (1) GO (1) google (1) gossip (1) Grupos de usuarios (1) Guadalajara (1) Guille Comunity Tour (2) Gusenet (9) GUSENET. (1) Huelga informáticos (1) IBEX 35 (1) Idioma (1) IFT (1) IISExpress (1) Indice de Fuerza Tecnica (1) informática (1) Informix (1) ING DIRECT (1) INGDIRECT (1) Ingeniería Informática (2) Inteligencia artificial (5) Intro (1) IOS (1) IPad (1) IPhone (1) IV Aniversario (1) JavaScript (2) JPA (2) keybd_event (1) LA CAIXA (1) La Pineda (1) ladroentidad (1) Lector RSS (2) LINQ (5) LINQ2XML (1) ListBox (1) Live Distributed Objects (1) llenar (1) LOG (1) Madrid .NET (1) MainMenu (1) MAP (1) MAP 2011 (1) MAR DEL PLATA (1) matemáticas (1) Matriculación (1) MDIList (1) MdiWindowsListItem (1) MenuItem (1) MenuStrip (1) Microsoft (18) Microsoft Active Professional (1) Miguel Egea (2) MSDE 2 (1) MSDE 2000 (1) MVVM Light (2) mysql (1) NAMESPACE (1) Needleman (2) NET (1) NS (1) Oferta empleo (1) Office 14 (1) Office 2007 (1) Office 2009 (1) ON ERROR (1) OOB (1) Oscar Montesinos (1) OWIN (1) OWIN Security middleware (1) Paginación (1) PDC (1) Pedro Hurtado (1) PINTARTECA (1) PrinterSettings (1) Process (1) ProcessStartInfo (1) Programador (1) Relacional (1) robo (1) RSS (1) Rubén Garrigós (1) Salvador Ramos (1) Santa Pola (1) scrape (1) scraping (1) ScrollBar (1) Secretaría (1) SendInput (1) SENDKEYS (1) Sergio Vázquez (1) Serializar (1) Silverlight 2.0 (2) Silverlight 4 (1) Silverlight 5 (3) Silverlight. (1) Sindicado (1) Sistema Personal de Trading (3) Sistemas Distribuidos (1) SOLID SUMMIT 2009 (1) SPT (2) SQL Server (3) SQL Server 2000 (2) SQL Server 2005 (2) SQL Server 2008 (3) SQL Server Denali (1) SQL Server Information Services. (1) SQLU (1) SSIS (1) SUMMIT SQL (1) Suspect (1) Syndication (1) TAB (1) Tablas (1) Tarragona (1) Token bearer (1) ToolStripMenuItem (1) ToString() (1) Traductor (1) transacciones (1) treeview (1) truco (1) TRY CATCH (1) UCI (1) Unience (2) Universad (1) Universidad Oberta Catalunya (2) UOC (8) Usuarios. (1) VB (1) VB6 (1) VB9 (1) VIAJAR (1) Vila-seca (1) VISUAL BASIC (3) Visual Basic. (1) visual studio (1) Visual Studio 2005 (1) Visual Studio 2008 (16) Visual Studio 2010 (2) Visual Studio 2013 (1) VS2010 (1) VSTA (1) VSTO (1) WCF (1) WEB API (1) web.config (1) WebClient (1) WF (1) windows (1) Windows 7 (3) Windows 8 (2) Windows Azure (1) Windows pone (1) Windows Server 2008 (1) Windows Vista (1) woff (1) WP7 (1) WPF (1) Wunsch (2) XAML (4) XDocument (1) XElement (1) XML (3) XNA (1) Yield (2)