2012-02-25 36 views

回答

3
var xdoc = XDocument.Load("http://blogs.technet.com/b/markrussinovich/atom.aspx"); 
XNamespace ns = XNamespace.Get("http://www.w3.org/2005/Atom"); 

var info = xdoc.Root 
      .Descendants(ns+"entry") 
      .Select(n => 
       new 
       { 
        Title = n.Element(ns+"title").Value, 
        Time = DateTime.Parse(n.Element(ns+"published").Value), 
       }).ToList(); 
1

試試這個LINQ到XML查詢,

XDocument xml = XDocument.Load("http://blogs.technet.com/b/markrussinovich/atom.aspx"); 
XNamespace ns = XNamespace.Get("http://www.w3.org/2005/Atom"); 
var xmlFeed = from post in xml.Descendants(ns + "entry") 
       select new 
       { 
        Title = post.Element(ns + "title").Value, 
        Time = DateTime.Parse(post.Element(ns + "published").Value) 
       }; 
8

.NET框架暴露了一組類和API,專門用於處理包括RSS 2.0和Atom 1.0在內的Syndicated XML Feeds,它們可以在System.ServiceModel.Syndication命名空間。

基本類爲:
System.ServiceModel.Syndication.SyndicationFeed代表Atom或RSS格式的XML Feed。
System.ServiceModel.Syndication.SyndicationItem表示飼料中的項,「入口」或「項」元件,但是這些被暴露的SyndicationFeed IEnumerable Items的屬性。

就我個人而言,我更喜歡使用System.ServiceModel.Syndication命名空間中暴露的類和API,而不是Linq to XML,因爲您直接使用強類型對象而不含糊不清的XElements。

  WebRequest request = WebRequest.Create(this.Url); 
      request.Timeout = Timeout; 

      using (WebResponse response = request.GetResponse()) 
      using (XmlReader reader = XmlReader.Create(response.GetResponseStream())) 
      { 
       SyndicationFeed feed = SyndicationFeed.Load(reader); 

       if (feed != null) 
       { 
        foreach (var item in feed.Items) 
        { 
         // Work with the Title and PubDate properties of the FeedItem 
        } 
       } 
      } 
+0

好的建議,因爲你可以添加一個超時屬性。 – ScottE 2012-03-26 17:51:40

+0

@ScottE您也可以在一個單獨的線程中調用WebResponse.GetResponse(),並使用超時來捕獲響應中的任何超時。 WebRequest.Timeout僅適用於初始服務器響應,如果您然後鬆開它將掛起的連接。 – Lloyd 2012-03-27 11:41:05