2012-04-02 160 views
0

我创建的窗口电话高音例子,得到了NullReferenceExceptionXML解析错误

我认为这可能是语法上表达的右侧不正确却说不出什么,为什么..

任何人都有一个想法,为什么这导致错误?

.xaml.cs:

public partial class MainPage : PhoneApplicationPage 
{ 
    // Constructor 
    public MainPage() 
    { 
     string url = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=noradio"; 

     WebClient twitter = new WebClient(); 
     twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted); 
     twitter.DownloadStringAsync(new Uri(url)); 
    } 

    void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 
     if (e.Error != null) 
      return; 

     XElement xmlTweets = XElement.Parse(e.Result); 

     listBox1.ItemsSource = from tweet in xmlTweets.Descendants("Status") 

     select new TweeterItem 
     { 
      ImageSource = tweet.Element("user").Element("profile_image_url").Value, 
      Message = tweet.Element("text").Value, 
      UserName = tweet.Element("user").Element("screen_name").Value, 
     }; 
    } 

的.xaml:

<ListBox Height="521" HorizontalAlignment="Left" Margin="0,131,0,0" Name="listBox1" VerticalAlignment="Top" Width="476"> 
<ListBox.ItemTemplate> 
<DataTemplate> 
<StackPanel Orientation="Horizontal" Height="132"> 
<Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/> 
<StackPanel Width="370"> 
<TextBlock Text="{Binding UserName}" Foreground="#FFC8AB14" FontSize="28" /> 
<TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" /> 
</StackPanel> 
</StackPanel> 
</DataTemplate> 
</ListBox.ItemTemplate> 
</ListBox> 
+1

你可以包含堆栈跟踪的例外发生在你的文章?我的赌注是,在你的虚线属性链中有一个空对象。 – 2012-04-03 09:57:49

+0

你说的没错,这里是异常详细信息: System.NullReferenceException了未处理 消息=的NullReferenceException 堆栈跟踪: 在XmlApp.MainPage.twitter_DownloadStringCompleted(对象发件人,DownloadStringCompletedEventArgs E) 在System.Net.WebClient.OnDownloadStringCompleted( DownloadStringCompletedEventArgs e) at System.Net.WebClient.DownloadStringOperationCompleted(Object arg) at – JoeLA 2012-04-03 14:52:18

+0

我得到了这个更具描述性的错误信息。你认为有些参考文献缺失? data.System.Collections.Generic.IEnumerator 。当前\t'System.Collections.Generic.IEnumerable '不包含'System'的定义,也没有接受第一个参数类型的扩展方法'System' 'System.Collections.Generic.IEnumerable '可以找到(你是否缺少使用指令或程序集引用?) – JoeLA 2012-04-03 16:29:26

回答

0

我平时做这样的事情,那么我可以事后检查空值:

 XmlReader xmlReader = XmlReader.Create(e.Result as Stream); 
     while (xmlReader.Read()) 
     { 
      if (xmlReader.NodeType == XmlNodeType.Element) 
      { 
       switch (xmlReader.Name) 
       { 
        case "profile_image_url": 
         ImageSource = xmlReader.ReadInnerXml(); 
         break; 
        case "text": 
         Message = xmlReader.ReadInnerXml(); 
         break; 
        case "screen_name": 
         UserName = xmlReader.ReadInnerXml(); 
         break; 
       } 
      } 
     }