如何使用System.ServiceModel.Syndication从RSS提要中读取“dc:creator”元素

时间:2010-04-01 16:55:10

标签: c# syndication dublin-core

方案

我正在使用一个RSS源,部分看起来像这样:

<item>
    <title>Blog Title Here</title>
    <link>http://blogurl.com/2010/03/23/title/</link>
    <comments>http://blogurl.com/2010/03/23/title/#comments</comments>
    <pubDate>Tue, 23 Mar 2010 10:44:54 +0000</pubDate>
    <dc:creator>AuthorName</dc:creator>
    <category><![CDATA[CategoryName]]></category>
    <guid isPermaLink="false">http://blogurl.com/?p=102</guid>
    <description><![CDATA[Description of post content]]></description>
    <content:encoded><![CDATA[Full blog post here]]></content:encoded>
</item>

我使用Rss20FeedFormatter获取SyndicationItems列表,如下所示:

List<SyndicationItem> items;
using (var reader = XmlReader.Create("http://blogurl.com/feed/"))
{
  var formatter = new Rss20FeedFormatter();
  formatter.ReadFrom(reader);
  items = formatter.Feed.Items.ToList();
}

问题

我不知道如何访问值 dc:creator 元素。我相信我需要以某种方式使用ElementExtensions,但我不确定语法,并且无法在任何地方找到示例。

1 个答案:

答案 0 :(得分:2)

这是一个简短的F#示例,希望能引导您使用一些有用的API:

let xml = @"
<rss version=""2.0"">
<channel xmlns:dc=""http://whatever.it.is/"" xmlns:content=""http://that.too/"">
<title>testing</title>
<item> 
    <title>Blog Title Here</title> 
    <link>http://blogurl.com/2010/03/23/title/</link> 
    <comments>http://blogurl.com/2010/03/23/title/#comments</comments> 
    <pubDate>Tue, 23 Mar 2010 10:44:54 +0000</pubDate> 
    <dc:creator>AuthorName</dc:creator> 
    <category><![CDATA[CategoryName]]></category> 
    <guid isPermaLink=""false"">http://blogurl.com/?p=102</guid> 
    <description><![CDATA[Description of post content]]></description> 
    <content:encoded><![CDATA[Full blog post here]]></content:encoded> 
</item> 
</channel>
</rss>
"

open System.Xml 
open System.IO
open System.ServiceModel.Syndication
let ReadIt() =
    use reader = XmlReader.Create(new StringReader(xml))
    let formatter = new Rss20FeedFormatter()
    formatter.ReadFrom(reader)
    let items = formatter.Feed.Items
    for item in items do
        // if I know there are dc:creator elements (that can deserialize with DataContract of type 'string')
        let dcCreators = item.ElementExtensions.ReadElementExtensions<string>("creator","http://whatever.it.is/")
        for dcc in dcCreators do
            printfn "dcc : %s" dcc
        // if just probing around
        for ee in item.ElementExtensions do
            printfn "extension `%s:%s'" ee.OuterNamespace ee.OuterName 
            use eer = ee.GetReader()
            let inner = eer.ReadInnerXml()
            printfn "    %s" inner
ReadIt()