Windows Phone 7从web服务读取并解析XML数据

本文关键字:XML 数据 读取 服务 Phone web Windows | 更新日期: 2023-09-27 18:29:45

我希望这些XML值从web服务读取到TextBlock,但这段代码会导致NullReferenceException。我确信这个web服务不是空的。我该如何解决这个问题???

导致异常的行被注释为:

// NOTE: NullReferenceException happens here
penalty = resultElements.Element("penalty").Value;

代码

namespace PhoneApp4
{
    public partial class pun : PhoneApplicationPage
    {
        WebClient pu;
        public pun()
        {
            InitializeComponent();
            pu = new WebClient();
            string pp ="http://82.212.89.6:888/mob/resources/punishments/studentPunishments/427400078/2";
            pu.DownloadStringAsync(new Uri(pp));
            pu.DownloadStringCompleted += new DownloadStringCompletedEventHandler(pun_DownloadStringCompleted);
            pu.DownloadProgressChanged += new DownloadProgressChangedEventHandler(pun_DownloadProgressChanged);
        }
        void pun_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (e.UserState as string == "mobiforge")
            {
                textBlock1.Text = e.BytesReceived.ToString() + " bytes received.";
            }
        }
        void pun_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null && !e.Cancelled)
            {
                XElement resultElements = XElement.Parse(e.Result);
                // NOTE: NullReferenceException happens here
                penalty = resultElements.Element("penalty").Value;
                semester = resultElements.Element("semester").Value;
                pun1.Text = penalty;
                ps1.Text = semester;
           }
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            MainPage tt = e.Content as MainPage;
            if (tt != null)
            {
                textBlock1.Text = tt.txtb1.Text;
            }
        }
        public string penalty { get; set; }
        public string semester { get; set; }
    }
}

Windows Phone 7从web服务读取并解析XML数据

它适用于我的

penalty = resultElements.Element("studentPunishmentsTable").Element("penalty").Value;
semester = resultElements.Element("studentPunishmentsTable").Element("semester").Value;

这是一个基于REST的WS吗??如果是,请考虑使用RestSharp。