1

Hi,

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

    }
Patrick
  • 21
  • 5
  • 1
    Use XmlSerializer Class https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx – Sybren Oct 06 '15 at 11:21

1 Answers1

1

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.

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

Community
  • 1
  • 1
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101