如何使用.Net Core从RSS源获取项目?

时间:2017-11-15 03:44:26

标签: f# .net-core

如何使用.Net Core从RSS源获取项目?

以下代码似乎不起作用:

open Microsoft.SyndicationFeed
open Microsoft.SyndicationFeed.Rss

[<Test>]
let ``Get links from iTunes RSS Feed`` () =

    let url = "http://www.pwop.com/feed.aspx?show=dotnetrocks&filetype=master&tags=F%23"
    use reader = XmlReader.Create(url)
    let feedReader = RssFeedReader(reader)

    let mutable linkTemplate = { 
        Title=         ""
        Url=           ""
    }

    let links =

        async {

            let links = Collections.Generic.List<Link>()

            while feedReader.Read() |> Async.AwaitTask |> Async.RunSynchronously do

                match feedReader.ElementType with
                | SyndicationElementType.Link ->
                    let item = feedReader.ReadLink() |> Async.AwaitTask |> Async.RunSynchronously                    
                    let link = { linkTemplate with Title= item.Title; Url= item.Uri.AbsolutePath }
                    links.Add(link)
                | _ -> ()

            return links

        } |> Async.RunSynchronously

    reader.Close()

    System.Diagnostics.Debug.WriteLine(links.[0].Title)

    links.[0].Title |> should not' (equal "")

具体而言,读取项目但读取后没有实际数据。

1 个答案:

答案 0 :(得分:3)

我按照建议使用了XElement类:

[<Test>]
let ``Get links from iTunes RSS Feed`` () =

    let toLink (item:XElement) = { 
        Id =          -1
        ProfileId =   "to be derived..."
        Title=        item.Element(XName.Get("title")) |> string
        Url=          item.Element(XName.Get("link"))  |> string
        Description = item.Element(XName.Get("description")) |> string
        ContentType=  Podcast |> contentTypeToString
        Topics =      []
        IsFeatured=   false
     }

    let baseAddress = "http://www.pwop.com/"
    let url = "feed.aspx?show=dotnetrocks&filetype=master&tags=F%23"
    use client = httpClient baseAddress

    let response = client.GetAsync(url) |> Async.AwaitTask 
                                        |> Async.RunSynchronously
    let links = 
        if response.IsSuccessStatusCode
           then let text = response.Content.ReadAsStringAsync()     |> Async.AwaitTask |> Async.RunSynchronously
                XElement.Parse(text).Descendants(XName.Get("item")) |> Seq.toList      |> List.map toLink
           else []

    links |> List.isEmpty |> should equal false