gpt4 book ai didi

c# - RSS 提要中 DateTime 解析的异常在 c# 中使用 SyndicationFeed

转载 作者:太空狗 更新时间:2023-10-29 17:37:07 24 4
gpt4 key购买 nike

我正在尝试使用 SyndicationFeed 对象解析 Rss2、Atom 提要。但是我在解析诸如 pubDate 之类的 DateTime 字段时遇到了 XmlExceptions

2012-01-17 08:01:06

public static List<SyndicationItem> getRssData(string url)
{
List<SyndicationItem> list = new List<SyndicationItem>();

WebClient client = new WebClient();
try
{
SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(url));
list = (from item in feed.Items select item).ToList();
}
catch (Exception e)
{
throw e;
}

return list;
}

网址链接http://news.163.com/special/00011K6L/rss_newstop.xml

<item id="2">
<title>...</title>
<link>...</link>
<description>......</description>
<pubDate>2012-01-17 12:09:29</pubDate><-----Exception
</item>

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

最佳答案

有一个解决方法 RSS20FeedFormatter throws exception trying to read some DateTime formats .

To work around this problem, create a custom XML reader that recognizes different date formats. The following is an example of a custom XML reader:

XmlReader r = new MyXmlReader(url);
SyndicationFeed feed = SyndicationFeed.Load(r);
Rss20FeedFormatter rssFormatter = feed.GetRss20Formatter();
XmlTextWriter rssWriter = new XmlTextWriter("rss.xml", Encoding.UTF8);
rssWriter.Formatting = Formatting.Indented;
rssFormatter.WriteTo(rssWriter);
rssWriter.Close();

..和前面代码中使用的类:

class MyXmlReader : XmlTextReader
{
private bool readingDate = false;
const string CustomUtcDateTimeFormat = "ddd MMM dd HH:mm:ss Z yyyy"; // Wed Oct 07 08:00:07 GMT 2009

public MyXmlReader(Stream s) : base(s) { }

public MyXmlReader(string inputUri) : base(inputUri) { }

public override void ReadStartElement()
{
if (string.Equals(base.NamespaceURI, string.Empty, StringComparison.InvariantCultureIgnoreCase) &&
(string.Equals(base.LocalName, "lastBuildDate", StringComparison.InvariantCultureIgnoreCase) ||
string.Equals(base.LocalName, "pubDate", StringComparison.InvariantCultureIgnoreCase)))
{
readingDate = true;
}
base.ReadStartElement();
}

public override void ReadEndElement()
{
if (readingDate)
{
readingDate = false;
}
base.ReadEndElement();
}

public override string ReadString()
{
if (readingDate)
{
string dateString = base.ReadString();
DateTime dt;
if(!DateTime.TryParse(dateString,out dt))
dt = DateTime.ParseExact(dateString, CustomUtcDateTimeFormat, CultureInfo.InvariantCulture);
return dt.ToUniversalTime().ToString("R", CultureInfo.InvariantCulture);
}
else
{
return base.ReadString();
}
}
}

关于c# - RSS 提要中 DateTime 解析的异常在 c# 中使用 SyndicationFeed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8891047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com