使用C#进行Xml解析的问题

时间:2014-06-03 11:29:01

标签: c# xml

我正在开发我的第一个Windows应用程序,我在解析Xml时面临一些问题,代码如下所示

 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;

             }

         }

     }

问题是没有调用Delegate TimeDownloaded。我使用相同的技术解析一个不同的URL,它很容易完成,但它在这种情况下不起作用。请帮助我,因为我对这个领域很新。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

关于获取节点的一些遗漏

输出是geonames / timezone / time,它在下面更正,也可以使用DownloadStringTaskAsync方法测试

[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; }
}

}

答案 1 :(得分:0)

您可以使用下面提到的代码。

        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;

         }

对于Windows Phone 8,您必须实现getResponse方法。

 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);
}