问题
I am tring to give an information from friendfeed API.
As you see in code, I am using an HttpRequest to get information. It's ok.
After that I am reading XML just fine with LINQ.
But now I create a "feed" class and I want to create an object for every returned value (i from finaltoclass).
How can I do this?
Can you help me with this?
Thank you.
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:
If you think to read it this way (dynamic feed class - without declaring feed
, entry
, via
and from
classes ):
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);
}
you will need Json.Net and this extension class
回答2:
Let's try this code
var finaltoclass = from i in final.Elements("entry")
select new entry (i.Element("body").Value, i.Element("id").Value, i.Element("url").Value );
回答3:
You need to add to an ObservableCollection
of entry.
来源:https://stackoverflow.com/questions/8185869/c-sharp-returned-xml-to-class