从XML而不是JSON C#asp.net读取

时间:2015-10-06 11:16:16

标签: c# asp.net json xml

您好日

今天我有一个代码从URL中检索JSON数据。它运作得很好。

但是现在我想做同样的事情,但我想从XML而不是JSON中检索。

我如何以最好的方式做到这一点?

提前致谢,

Json网址:http://api.namnapi.se/v2/names.json?limit=3
XML网址:http://api.namnapi.se/v2/names.xml?limit=3

    public class Data
    {
        public List<Objects> names { get; set; }
    }

    public class Objects
    {
        public string firstname { get; set; }
        public string surname { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        WebClient client = new WebClient();
        string json = client.DownloadString("http://api.namnapi.se/v2/names.json?limit=3");

        Data result = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Data>(json);

        foreach (var item in result.names)
        {
            Label.Text += (item.firstname + " " + item.surname + "<br />");
        }

    }

1 个答案:

答案 0 :(得分:1)

有几种方法可以在C#中解析XML。

例如,您可以使用XmlDocument

WebClient client = new WebClient();
string xml = client.DownloadString("http://api.namnapi.se/v2/names.xml?limit=3");

XmlDocument document = new XmlDocument();
document.LoadXml(xml);

foreach (XmlElement node in document.SelectNodes("names/name"))
{
    Label.Text += String.Format("{0} {1}<br/>", 
        node.SelectSingleNode("firstname").InnerText,  
        node.SelectSingleNode("lastname"));
}

还有一些方法可以使用XmlSerializer将XML序列化到您自己的类中,XmlTextReaderLinq2Xml等。选择最合适的方法。

在C#中阅读有关XML解析的更多信息:

How do I read and parse an XML file in C#?
XML Parsing - Read a Simple XML File and Retrieve Values

Stackoverflow和其他Internet资源上有很多关于此主题的信息。

P.S。在我看来,最好使用JSON,因为它可以节省高达千兆字节的网络流量。