Consuming a REST XML web service

前端 未结 4 803
终归单人心
终归单人心 2020-12-13 16:11

I\'m trying to consume the following web service http://ipinfodb.com/ip_location_api.php this web service returns an xml response, the code below gets the XML response, but

4条回答
  •  暖寄归人
    2020-12-13 16:37

    My solution would be:

    • run the xsd.exe utility on your result XML twice to convert it to a XSD (first step) and a C# class (second step) - this would give you a C# class Response

    • next, you can easily deserialize the response into an instance of that class:

      HttpWebRequest request = WebRequest.Create("http://api.ipinfodb.com/v2/ip_query.php?key=--yourkey--&ip=74.125.45.100&timezone=true") as HttpWebRequest;
      
      XmlSerializer ser = new XmlSerializer(typeof(Response));
      
      WebResponse response = request.GetResponse();
      var result = ser.Deserialize(response.GetResponseStream());
      

      and now your result would contain an instance of Response, with all the elements as nice fields in your object.

    Read more about xsd.exe on its MSDN doc page.

提交回复
热议问题