简体   繁体   中英

Read from XML instead of JSON C# asp.net

Today I have a code that retrieves the JSON data from a URL. It works perfectly.

But now I want to do just the same, but I want to retrieve from an XML instead of JSON.

How do I do it the best way?

Thanks in advance,

Json URL: http://api.namnapi.se/v2/names.json?limit=3
XML URL: 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 />");
        }

    }

There are several ways to parse your XML in C#.

For example, you can use 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"));
}

There are also such approaches as using XmlSerializer for serializing XML into your own classes, XmlTextReader , Linq2Xml etc. Pick the most suitable one.

Read more about XML parsing in C#:

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

There is a lot of information on this topic on Stackoverflow and other Internet resources.

PS In my opinion, it is better to use JSON because it can save up to gigabytes of network traffic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM