2011-05-12 40 views
1

我正在開發Windows Phone 7的示例Twitter應用程序。在我的代碼中顯示用戶的一些細節,使用了下面的代碼。無法解析使用Linq的xml查詢

void ShowProfile() 
    { 
     WebClient client = new WebClient(); 
     client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Profile_DownloadCompleted); 
     client.DownloadStringAsync(new Uri("http://api.twitter.com/1/users/show.xml?user_id=" + this.id)); 
    } 

    void Profile_DownloadCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 
     if (e.Error != null) 
     { return; } 
     if (e.Result == null) MessageBox.Show("NUlllllllllll"); 
     XElement Profile = XElement.Parse(e.Result); 

    var ProfileDetails = (from profile in Profile.Descendants("user") 
          select new UserProfile 
          { 
           UserName = profile.Element("screen_name").Value, 
           ImageSource = profile.Element("profile_image_url").Value, 
           Location = profile.Element("location").Value, 
           TweetsCount = profile.Element("statuses_count").Value, 
          }).FirstOrDefault(); 

     LayoutRoot.DataContext = ProfileDetails; 
} 

這裏,LayoutRoot是網格名稱。但數據綁定不起作用。 事實上,當保持一個斷點時,似乎在ProfileDetails對象中沒有數據。但我可以觀察到,e.Result包含XML格式所需的數據。 任何身體都能想出我要去哪裏? 在此先感謝。

回答

2

您已使用XElement.Parse,因此Profile代表API請求已返回的單根<user>。然後你試圖尋找其中的user元素,這當然是沒有意義的。

嘗試用XDocument.Parse代替。當該列表只能包含1個條目時,是否真的有意義地將IEnumerable<UserProfile>分配給數據上下文?

+0

感謝您的回答。我試過XDocument.Parse,它工作。 – nkchandra 2011-05-13 05:43:29

+0

即將到來的第二點您提出,事實上,Linq查詢不返回IEnumerable ,返回一個UserProfile對象,該ProfileDetails持有。這是因爲FirstOrDefault()方法。當然,網絡查詢的響應也會返回單個用戶的詳細信息,而不是列表。但你清除了我的懷疑,節省了我的時間。再次感謝。 – nkchandra 2011-05-13 05:47:54