dhee
dhee

Reputation: 47

Problems with Xml parsing using C#

I am developing my first windows App and I am facing some Problems while parsing an Xml,the code is as shown below

 public void TimeParsing(string lat, string lon)
       {

           string urlbeg = "http://api.geonames.org/timezone?lat=";
           string urlmid = "&lng=";
           string urlend = "&username=dheeraj_kumar";


           WebClient downloader = new WebClient();
           Uri uri = new Uri(urlbeg + lat + urlmid + lon + urlend, UriKind.Absolute);
           downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TimeDownloaded);
           //downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TimeDownloaded);
           downloader.DownloadStringAsync(uri);
       }

     private void TimeDownloaded(object sender, DownloadStringCompletedEventArgs e)
     {
         if (e.Result == null || e.Error != null)
         {
             MessageBox.Show("Invalid");
         }
         else
         {
             XDocument document = XDocument.Parse(e.Result);
             var data1 = from query in document.Descendants("geoname")
                         select new Country
                         {
                             CurrentTime = (string)query.Element("time"),



                         };
             foreach (var d in data1)
             {
                 time = d.CurrentTime;
                 MessageBox.Show(d.CurrentTime);
                 // country = d.CountryName;

             }

         }

     }

The problem is that the Delegate TimeDownloaded is not being called. I used the same technique is parse a different URL and it was done easily but its not working in this case.Kindly Help me as I am pretty new to this field. Thanks in advance.

Upvotes: 0

Views: 134

Answers (2)

Dhaval Patel
Dhaval Patel

Reputation: 7601

you can use the below mentioned code.

        Uri uri = new Uri(urlbeg + lat + urlmid + lon + urlend, UriKind.Absolute);
          HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(uri);
        //This time, our method is GET.
         WebReq.Method = "GET";
        //From here on, it's all the same as above.
        HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

        //Now, we read the response (the string), and output it.
        Stream Answer = WebResp.GetResponseStream();
        StreamReader _Answer = new StreamReader(Answer);
        string s = _Answer.ReadToEnd();

        XDocument document = XDocument.Parse(s);
         var data1 = from query in document.Descendants("geoname")
                     select new Country
                     {
                         CurrentTime = (string)query.Element("time"),



                     };
         foreach (var d in data1)
         {
             time = d.CurrentTime;
             MessageBox.Show(d.CurrentTime);
             // country = d.CountryName;

         }

for Windows Phone 8 you have to implement the getResponse Method.

 public static System.Threading.Tasks.Task<System.Net.WebResponse> GetResponseAsync(this System.Net.WebRequest wr)
{
    return Task<System.Net.WebResponse>.Factory.FromAsync(wr.BeginGetResponse, wr.EndGetResponse, null);
}

Upvotes: 0

JFM
JFM

Reputation: 753

Theres a few misses regarding fetching the nodes

The output is geonames/timezone/time, it's corrected below, also testable using the method DownloadStringTaskAsync instead

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public async Task TestMethod1()
    {
        await TimeParsing("-33.8674869", "151.20699020000006");

    }

    public async Task TimeParsing(string lat, string lon)
    {

        var urlbeg = "http://api.geonames.org/timezone?lat=";
        var urlmid = "&lng=";
        var urlend = "&username=dheeraj_kumar";
        var downloader = new WebClient();
        var uri = new Uri(urlbeg + lat + urlmid + lon + urlend, UriKind.Absolute);
        downloader.DownloadStringCompleted += TimeDownloaded;
        var test = await downloader.DownloadStringTaskAsync(uri);

        Console.WriteLine(test);
    }

    private void TimeDownloaded(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Result == null || e.Error != null)
        {
            Console.WriteLine("Invalid");
        }
        else
        {
            var document = XDocument.Parse(e.Result);
            var data1 = from query in document.Descendants("timezone")
                        select new Country
                        {
                            CurrentTime = (string)query.Element("time"),



                        };

            foreach (var d in data1)
            {
                Console.WriteLine(d.CurrentTime);
            }

        }

    }
}

internal class Country
{
    public string CurrentTime { get; set; }
}

}

Upvotes: 1

Related Questions