【问题标题】:Windows Phone 7 read and parse XML data from web serviceWindows Phone 7 从 Web 服务读取和解析 XML 数据
【发布时间】:2012-04-03 07:02:56
【问题描述】:

我希望将这些 XML 值从 Web 服务读取到 TextBlock,但此代码会导致 NullReferenceException。我确信网络服务不为空。这个问题怎么解决???

导致异常的行被注释为:

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

【问题讨论】:

  • 哪些行会导致 NullReferenceException?什么是堆栈跟踪?
  • penalty = resultElements.Element("penalty").Value;学期 = resultElements.Element("学期").Value;这是发生异常

标签: c# xml parsing windows-phone-7


【解决方案1】:

对我有用

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多