Reputation: 105
I am using this API to find the country of a user. I am able to find the country on a web page in XML format. Here you can see XML file example. But the problem is i can not read this XML in my c# code. Here is my code
string UserIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
string ApiKey = "5d3d0cdbc95df34b9db4a7b4fb754e738bce4ac914ca8909ace8d3ece39cee3b";
string Url = "http://api.ipinfodb.com/v3/ip-country/?key=" + ApiKey + "&ip=" + UserIP;
XDocument xml = XDocument.Load(Url);
But this code returns following exception on loading the xml.
System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
Please describe the exact method to read this XML.
Upvotes: 0
Views: 3874
Reputation: 111850
I'll say that it isn't an XML but simply a string subdivided by ;
:
By giving an impossible IP address we can see that it's so composed:
OK;;74.125.45.100;US;UNITED STATES
ERROR;Invalid IP address.;127.0.0.1.1;;
OK/ERROR
If ERROR, complete ERROR message
IP Address
Abbreviation of country
Country name
This code should do:
string userIP = "127.0.0.1";
string apiKey = "5d3d0cdbc95df34b9db4a7b4fb754e738bce4ac914ca8909ace8d3ece39cee3b";
string url = "http://api.ipinfodb.com/v3/ip-country/?key=" + apiKey + "&ip=" + userIP;
WebRequest request = WebRequest.Create(url);
using (var response = (HttpWebResponse)request.GetResponse())
{
// We try to use the "correct" charset
Encoding encoding = response.CharacterSet != null ? Encoding.GetEncoding(response.CharacterSet) : null;
using (var sr = encoding != null ? new StreamReader(response.GetResponseStream(), encoding) :
new StreamReader(response.GetResponseStream(), true))
{
var response2 = sr.ReadToEnd();
var parts = response2.Split(';');
if (parts.Length != 5)
{
throw new Exception();
}
string okError = parts[0];
string message = parts[1];
string ip = parts[2];
string code = parts[3];
string country = parts[4];
}
}
Upvotes: 2
Reputation: 22323
from the IP Location XML API Documentation: API Parameter format, required = false, default = raw, values = raw, xml, json. so I have tested it and string Url = "http://api.ipinfodb.com/v3/ip-country/?key=" + ApiKey + "&ip=" + UserIP + "&format=xml"
gives a parsable xml result.
Upvotes: 1
Reputation: 1866
Here is what I'd do:
Upvotes: 1