2010-02-24 18 views
6

Estoy tratando de analizar Rss2, alimentaciones Atom utilizando los objetos SyndicationFeedFormatter y SyndicationFeed. Pero obtengo XmlExceptions mientras analizo el campo DateTime como pubDate y/o lastBuildDate.Excepciones con el análisis de DateTime en RSS en C#

Mie 24 Feb 2010 18:56:04 GMT + 00: 00 no funciona

Mie 24 Feb 2010 18:56:04 GMT funciona

lo tanto, es tirar debido a la zona horaria campo.

Como solución temporal, corregiría manualmente esos nodos DateTime, detectando XmlException, cargando el Rss en un XmlDocument, reparando el valor de esos nodos, creando un nuevo XmlReader y luego devolviendo el formateador de este nuevo XmlReader objeto (código no mostrado). Pero para que este enfoque funcione, necesito saber de antemano qué nodos causan una excepción.

 SyndicationFeedFormatter syndicationFeedFormatter = null; 
     XmlReaderSettings settings = new XmlReaderSettings(); 
     using (XmlReader reader = XmlReader.Create(url, settings)) 
     { 
      try 
      { 
       syndicationFeedFormatter = SyndicationFormatterFactory.CreateFeedFormatter(reader); 
       syndicationFeedFormatter.ReadFrom(reader); 
      } 
      catch (XmlException xexp) 
      { 
       // fix those datetime nodes with exceptions and read again. 
      } 
     return syndicationFeedFormatter; 
    } 

RSS: http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&q=test&cf=all&output=rss

detials excepción: Error

XmlException en la línea 1 posición 376. Se encontró un error al analizar un valor DateTime en el XML.
en System.ServiceModel.Syndication.Rss20FeedFormatter.DateFromString (String dateTimeString, lector de XmlReader)
en System.ServiceModel.Syndication.Rss20FeedFormatter.ReadXml (XmlReader lector, resultado SyndicationFeed) en System.ServiceModel.Syndication. Rss20FeedFormatter.ReadFrom (XmlReader lector) a las ... CS: línea 171

<rss version="2.0"> 
    <channel> 
    ... 
    <pubDate>Wed, 24 Feb 2010 18:56:04 GMT+00:00</pubDate> 
    <lastBuildDate>Wed, 24 Feb 2010 18:56:04 GMT+00:00</lastBuildDate> <-----exception 
    ... 
    <item> 
     ... 
     <pubDate>Wed, 24 Feb 2010 16:17:50 GMT+00:00</pubDate> 
     <lastBuildDate>Wed, 24 Feb 2010 18:56:04 GMT+00:00</lastBuildDate> 
    </item> 
    ... 
    </channel> 
</rss> 

¿hay una mejor manera de lograr esto? Por favor ayuda. Gracias.

Respuesta

9

Aquí está mi solución hacky para leer feeds RSS de Google Noticias.

string xml; 
using (WebClient webClient = new WebClient()) 
{ 
    xml = Encoding.UTF8.GetString(webClient.DownloadData(url)); 
} 
xml = xml.Replace("+00:00", ""); 
byte[] bytes = System.Text.UTF8Encoding.ASCII.GetBytes(xml); 
XmlReader reader = XmlReader.Create(new MemoryStream(bytes)); 
SyndicationFeed feed = SyndicationFeed.Load(reader); 
+2

Niza solución. Odio que tengamos que hacer esto. Mis amigos de PHP también me miran de reojo cuando hablo de un servicio arrojando errores sobre algo trivial como este. –

+0

Esta es una buena idea, pero ¿y si la cadena no es 00:00, si se trata de otra zona horaria? Creo que es una buena práctica usar Regex aquí en lugar de Reemplazar –

0

para convertir PublishDate en RSS a su fecha y hora del ordenador se podría escribir estas líneas

string dateStr = item.PublishDate.ToString("ddd MMM dd HH:mm:ss zzzz yyyy"); 
        DateTime PostDate = DateTime.ParseExact(dateStr, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture);