c# - 如何将 ListBox 绑定(bind)到 XML 文件中的对象列表?

标签 c# .net linq-to-xml

你好,我正在尝试解析一个包含用户名列表的简单 xml 文件,然后将结果绑定(bind)到列表框

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;

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

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

最佳答案

感谢您的回复!我研究了代码并提出了一个可行的解决方案。

 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;

关于c# - 如何将 ListBox 绑定(bind)到 XML 文件中的对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16587895/

相关文章:

c# - XDocument 删除节点

c# - 将对象转换为正确的类型

c# - 没有可用的 System.Runtime.Caching?

c# - 为 WP 游戏库制作正确的 URI

.net - LINQ 到 XML : how do I get only direct descendants of an XElement?

c# - CallNamedPipe & NamedPipeServerStream,访问被拒绝?

c# - Facebook 身份验证和 Asp.Net 成员资格

c# - DataRow GetHashCode() 方法值在编辑行后不会改变

.net - 为什么我不能在后代 ("XName"上调用 FirstOrDefault )

c# - 使用 XDocument 搜索和提取数据