C# - Problems reading data from an XML returned from a site

Asked

Viewed 177 times

4

I want to take the Location of an external IP and for that I used a site where I simply put the IP I want and it returns the XML with the information.

Example:

freegeoip.net/xml/4.2.2.2

that is to say:

freegeoip.net/[tipo]/[ip]

For this I am taking all the characters of this site and trying to work with a string containing an XML inside and returning what I want:

public static string getLocationIPAddress()
{
        string country = null;
        string state = null;
        string city = null;

        System.Net.WebClient t = new System.Net.WebClient();
        string site = t.DownloadString("https://freegeoip.net/xml/" 
                                              + getExternIPAdrress());          

        XElement xml = XElement.Parse(site);           

        country = xml.Attribute("CountryName").Value;
        state = xml.Attribute("RegionName").Value;
        city = xml.Attribute("City").Value;   

        return "País: " + country + "Estado: " + state + "Cidade: " + city;

}

I tried to take the \n\t that appear on the string site, I have tried to work with other functions of the XElement and I have also searched for other classes but most work with file and not with string.

  • What’s the matter?

  • It generates an Exception at: country = xml. Attribute("Countryname"). Value; and dai does not pass.

2 answers

0


The return in XML maybe not the best, but there is a way:

Example of the return:

<Response>
    <IP>8.8.8.8</IP>
    <CountryCode>US</CountryCode>
    <CountryName>United States</CountryName>
    <RegionCode>CA</RegionCode>
    <RegionName>California</RegionName>
    <City>Mountain View</City>
    <ZipCode>94035</ZipCode>
    <TimeZone>America/Los_Angeles</TimeZone>
    <Latitude>37.386</Latitude>
    <Longitude>-122.0838</Longitude>
    <MetroCode>807</MetroCode>
</Response>

Utilize XDocument

public static string getLocationIPAddress()
{             
    System.Net.WebClient t = new System.Net.WebClient();
    string site = t.DownloadString("https://freegeoip.net/xml/" 
                                               + getExternIPAdrress());


    var xml = (from d in XDocument.Parse(site).Descendants("Response")
               let ip = d.Element("IP")
               let countryCode = d.Element("CountryCode")
               let countryName = d.Element("CountryName")
               let regionCode = d.Element("RegionCode")
               let regionName = d.Element("RegionName")
               let city = d.Element("City")
               let zipCode = d.Element("ZipCode")
               let timeZone = d.Element("TimeZone")
               let latitude = d.Element("Latitude")
               let longitude = d.Element("Longitude")
               let metroCode = d.Element("MetroCode")
               select new
               {
                   IP = ip.Value,
                   CountryCode = countryCode.Value,
                   CountryName = countryName.Value,
                   RegionCode = regionCode.Value,
                   RegionName = regionName.Value,
                   City = city.Value,
                   ZipCode = zipCode.Value,
                   TimeZone = timeZone.Value,
                   Latitude = latitude.Value,
                   Longitude = longitude.Value,
                   MetroCode = metroCode.Value

               })
              .FirstOrDefault();



    return "País: " 
            + xml.CountryName + "Estado: " 
            + xml.RegionName + "Cidade: " 
            + xml.City;    
}
  • Your method worked perfectly! Only this wrong on the return of it, in which you Countrycode instead of Regionname for the State. Thank you so much for your help. I am new here, where I click here to say that your answer was correct?

  • 1

    And out of curiosity, what would be the best return to work?

  • @Amzero The best return would be json, I am changing the answer by the flagged detail and to mark as correct below the arrow that points down has a check just click on top.

0

Using Xdocument you can do your parser as follows:

public static string getLocationIPAddress()
{
    var result = string.Empty;

    using (var client = new System.Net.WebClient())
    {
        var xmlResponse = client.DownloadString("https://freegeoip.net/xml/4.2.2.2");
        var parsedDocument = XDocument.Parse(xmlResponse);

        var rootElements = from items 
            in parsedDocument.Descendants("Response")
            select items;

        var countryName = rootElements.Descendants("CountryName").FirstOrDefault();
        var regionName = rootElements.Descendants("RegionName").FirstOrDefault();
        var cityName = rootElements.Descendants("City").FirstOrDefault();

        if (countryName != null && regionName != null && cityName != null)
            result = $"País: {countryName.Value}; Estado: {regionName.Value}; Cidade: {cityName.Value};";
    }

    return result;
}

I made some modifications in your methods but returns the expected result.

You can also search a little more about Xdocument and how to use it in this link: https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.110). aspx

  • Your method worked perfectly! thanks for the help. I’ll give a check on the link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.