如何将ListBox绑定到XML文件中的对象列表?

时间:2013-05-16 12:47:30

标签: c# .net linq-to-xml

您好我正在尝试解析包含用户名列表的简单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;

这样可行,但只返回第一个用户。是否有另一种解析/循环遍历此文档然后将其绑定到列表框的方法?

大家好,感谢您的回复!我玩了代码并提出了一个有效的解决方案。它在下面的答案中

2 个答案:

答案 0 :(得分:1)

感谢您的回复!我玩了代码并想出了一个有效的解决方案。

 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;

答案 1 :(得分:0)

我想你想要这样的东西:

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