0

I'm pulling some xml from a web api and trying to deserialize it to a Forecast object (which I defined using the "paste xml as classes"), but I'm getting the error "Error in XML Document (1,1)". Here is my code:

public static Forecast getWeather(int zip)
   {
        string url = "http://api.weatherunlocked.com/api/forecast/us." + zip.ToString() + "?app_id={myId}&app_key={mykey}";
        using (WebClient client = new WebClient())
        {
            string xml = client.DownloadString(url);
            var reader = new StringReader(xml);
            var serializer = new XmlSerializer(typeof(Forecast));
            var instance = (Forecast)serializer.Deserialize(reader);
            return instance;
        }

   }

When I pasted the XML as classes, it said there were some errors in the XML; I had to take out a few < characters that shouldn't be there. Is it possible that, since I cannot actually change the XML from the api call, these extra characters are making it invalid XML, and so it's never going to work? The XML is over 2000 lines so I don't think it'd be reasonable to try to go through the string and take out all of those characters. Or, is the problem something else in my code that's fixable? If anyone else has used the Weather Unlocked api or had this same problem, some sample code would be awesome.

issharp
  • 310
  • 6
  • 22
  • 1. Are you sure you are getting xml and not an html error page? 2. If their xml is malformed that is a big problem. 3. are you able to request json instead? (many apis allow it) – Crowcoder Jun 16 '16 at 18:42
  • Maybe I miss something but to me it looks as if their API only returns json. Also I'd rather try using [HttpRequest](https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.110).aspx) instead of WebClient. – Filburt Jun 16 '16 at 18:44
  • I'm getting xml when I put in the url with my api id and key. They give mixed messages about JSON, but essentially you can't get the website to display JSON. They said you could set your accept headers to JSON and then get the input as JSON but I don't know what that means/how to do it. If someone does know, I'm happy to switch to that method. – issharp Jun 16 '16 at 18:58
  • The encoding problem I feel. – Alexander Petrov Jun 16 '16 at 19:37
  • Try setting the `WebClient` encoding according to this answer: [WebClient.DownloadString() returns string with peculiar characters](https://stackoverflow.com/questions/4716470/webclient-downloadstring-returns-string-with-peculiar-characters/30049848#30049848). – dbc Jun 16 '16 at 19:39

0 Answers0