Search code examples
c#xmlxmlhttprequest

How to assign value from url xml response to a variable in visual studio?


I have a section of code that looks at the URL "https://freegeoip.net/xml/" and creates a XML Document. The xml from that URL looks like:

<Response>
    <IP>111.11.1.111</IP>
    <CountryCode>GB</CountryCode>
    <CountryName>United Kingdom</CountryName>
    <RegionCode>ENG</RegionCode>
    <RegionName>England</RegionName>
    <City></City>
    <ZipCode></ZipCode>
    <TimeZone>Europe/London</TimeZone>
    <Latitude>22</Latitude>
    <Longitude>0.9</Longitude>
    <MetroCode>0</MetroCode>
</Response>

I can see that there is a InnXML and a OuterXML that has the field and the values.

string url = @"https://freegeoip.net/xml/";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);

I would like to assign certain field of this XML Document to variables such as: -RegionName -City -Latitude -Longitude


Solution

  • One option is to get the specific properties with SelectSingleNode

    XmlNode node = xmlDoc .SelectSingleNode("//Response//RegionName");
    var regionName = node.InnerText;
    

    The other one is to deserialize the xml to object:

    XmlSerializer serializer = new XmlSerializer(typeof(Response));
    var stringReader = new StringReader(thexml);
    Response response = (Response)serializer.Deserialize(stringReader);
    
    
    public class Response
    {
        public string IP { get; set; }
        public string CountryCode { get; set; }
        public string CountryName { get; set; }
        public string RegionCode { get; set; }
        public string RegionName { get; set; }
        public string City { get; set; }
        public string ZipCode { get; set; }
        public string TimeZone { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string MetroCode { get; set; }
    }
    

    Now you have everything you need already in the response variable.

    Update

    To get the xml from a url:

    XmlTextReader reader = new XmlTextReader (URLString);
    Response response = (Response)serializer.Deserialize(reader);