簡體   English   中英

如何將ListBox綁定到XML文件中的對象列表?

[英]How do I bind a ListBox to a list of objects from an XML file?

您好,我正在嘗試解析一個包含用戶名列表的簡單xml文件,然后將結果綁定到列表框

xml看起來像這樣

<friends type = Array>
   <userId> xxxx </userId>
   <userId> yyyy </userId>
   <userId> zzzz </userId>
   <userId> wwww </userId>
         ...
   <userId> aaaa </userId>
</friends>

我的解析代碼如下所示

 XDocument friendFeed = XDocument.Load(new StringReader(response.Content)); var friendsData = from query in friendFeed.Descendants("friends") select new Friend { userId = (string)query.Element("userId"), profileImage = imageurl + (string)query.Element("userId") + "/avatar.png" }; friendListBox.ItemsSource = friendsData; 

此方法有效,但僅將第一個用戶返回給一個用戶。 還有另一種方法來解析/循環瀏覽此文檔,然后將其綁定到列表框嗎?

大家好,感謝您的回復! 我試用了代碼,並提出了一個可行的解決方案。 它在下面的答案中

感謝您的回復! 我試用了代碼,並提出了一個可行的解決方案。

 XDocument friendFeed = XDocument.Load(new StringReader(response.Content));

                List<string> values = new List<string>();

                 foreach (XElement item in friendFeed.Descendants("userId"))
                 {

                      values.Add(item.Value);

                 }

                 var friends = from query in values
                               select new Friend
                               {
                                   userId = query,
                                   profileImage = imageurl + query + "/avatar.png"
                               };
                 friendListBox.ItemsSource = friends;

我想你想要這樣的東西:

var friend = Xmldoc.SelectNodes("/");  
foreach (XmlNode friend in friends )  
{    
   var userIds= person.ChildNodes;      
   foreach(XmlNode userId in userIds )     
   {       //get the userId   
   }  
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM