2012-04-02 152 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; 
       } 
      } 
     }