本文介绍了C#将.XML返回类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正准备从friendfeed API提供信息.

I am tring to give an information from friendfeed API.

正如您在代码中看到的那样,我正在使用HttpRequest来获取信息.没关系.

As you see in code, I am using an HttpRequest to get information. It's ok.

那之后,我使用LINQ可以很好地阅读XML.

After that I am reading XML just fine with LINQ.

但是现在我创建一个"feed"类,并且我想为每个返回的值(finaltoclass中的i)创建一个对象.

But now I create a "feed" class and I want to create an object for every returned value (i from 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();
        }
    }
}

推荐答案

如果您想以此方式阅读(动态供稿类-未声明feedentryviafrom类):

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);
}

您将需要 Json.Net 扩展类

这篇关于C#将.XML返回类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 20:24