2011-11-18 100 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