代码之家  ›  专栏  ›  技术社区  ›  hIpPy

C中RSS提要中的DateTime分析异常#

  •  6
  • hIpPy  · 技术社区  · 15 年前

    我正在尝试使用SyndicationFeedFormatter和SyndicationFeed对象解析Rss2、Atom提要。但我在解析日期时间字段(如pubDate和/或lastbuildate)时遇到了XmlExceptions。

    2010年2月24日星期三18:56:04 GMT+00:00不起作用

    2010年2月24日星期三18:56:04 GMT工作

    所以,这是因为时区字段的缘故。

    作为一种解决方法,对于熟悉的提要,我将手动修复这些DateTime节点,方法是捕获XmlException,将Rss加载到XmlDocument中,修复这些节点的值,创建一个新的XmlReader,然后从这个新的XmlReader对象返回格式化程序(代码未显示)。但要使这种方法起作用,我需要事先知道哪些节点会导致异常。

            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

    例外详细信息:

    第1行位置出现XmlException错误 解析XML中的DateTime值时遇到错误。
    在 系统服务模型。银团。Rss20FeedFormatter。DateFromString(字符串 dateTimeString,XmlReader reader)
    在 系统服务模型。银团。Rss20FeedFormatter。ReadXml(XmlReader 读卡器,SyndicationFeed结果)位于 系统服务模型。银团。Rss20FeedFormatter。ReadFrom(XmlReader 读卡器)位于。。。cs:第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>
    

    有没有更好的方法来实现这一点?请帮忙。谢谢

    2 回复  |  直到 15 年前
        1
  •  10
  •   Michał Powaga Mohamed Aslam    13 年前

    以下是我阅读谷歌新闻RSS提要的黑客解决方法。

    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
  •  0
  •   Hussein Alrubaye    9 年前

    要将RSS中的PublishDate转换为您的计算机日期时间,您可以编写以下行

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