【问题标题】:Read from XML instead of JSON C# asp.net从 XML 而不是 JSON C# asp.net 读取
【发布时间】:2016-01-03 06:54:54
【问题描述】:

嗨,

今天我有一个从 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 />");
        }

    }

【问题讨论】:

标签: c# asp.net json xml


【解决方案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 和其他互联网资源上有很多关于这个主题的信息。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多