2011-11-18 104 views
1

我正在努力提供來自friendfeed API的信息。C#將.XML返回到類

正如您在代碼中看到的,我使用HttpRequest來獲取信息。沒關係。

之後,我正在用LINQ閱讀XML。

但現在我創建一個「feed」類,我想爲每個返回值(我從finaltoclass)創建一個對象。

我怎樣才能做到這一點?

你能幫我嗎?

謝謝。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.IO; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 

     class feed { } 
     public class entry { 
      string body; 
      string id; 
      string url; 

      public entry(string a, string b, string c) 
      { 
       body = a; 
       id = b; 
       url = c; 
      } 
     } 
     static void Main(string[] args) 
     { 
      string username = "semihmasat"; 

      WebRequest ffreq = WebRequest.Create("http://friendfeed-api.com/v2/feed/" + username + "?format=xml"); 

      WebResponse ffresp = ffreq.GetResponse(); 

      Console.WriteLine(((HttpWebResponse)ffresp).StatusDescription); 
      Stream stream = ffresp.GetResponseStream(); 
      StreamReader reader = new StreamReader(stream); 
      string respfinal = reader.ReadToEnd(); 
      reader.Close(); 

      XElement final = XElement.Load("http://friendfeed-api.com/v2/feed/" + username + "?format=xml"); 

      var finaltoclass = from i in final.Elements("entry") 
           select i; 

      foreach (XElement i in finaltoclass) { 
       string body= i.Element("body").Value; 
       string id= i.Element("id").Value; 
       string url= i.Element("url").Value; 

       Console.WriteLine("{0},{1},{2}", body, id, url); 
      } 

      Console.ReadLine(); 
     } 
    } 
} 

回答

1

如果你想閱讀這種方式(動態飼料級 - 不宣feedentryviafrom類):

dynamic feed = new Uri("http://friendfeed-api.com/v2/feed/" + username + "?format=json").GetDynamicJsonObject(); 
foreach (var entry in feed.entries) 
{ 
    Console.WriteLine(entry.from.name + "> " + entry.body + " " + entry.url); 
} 

您需要Json.Netthis擴展類

+0

這是不同於linq的權利? (json.net)我需要linq來使用它。實際上我是新的,現在我必須決定學什麼。 – NotNicolasCage

+0

否它不是linq。你必須寫的所有代碼如上所述。沒有xml解析,沒有類聲明。 –

+0

嗯,謝謝。這看起來更加有用和簡單。現在我看到很多我們網站的api使用json。我現在不需要學習linq。再次感謝:) – NotNicolasCage

0

您需要添加到條目的ObservableCollection

1

讓我們試試這個代碼

var finaltoclass = from i in final.Elements("entry") 
    select new entry (i.Element("body").Value, i.Element("id").Value, i.Element("url").Value); 
+0

嗯,我想我可以使用這個。謝謝。 – NotNicolasCage

+0

但是,我將只有一個條目obj對嗎? – NotNicolasCage

+0

不,你會得到IEnumerable