微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#Foreach XML节点

我正在尝试将XML文件中的所有节点添加到listView中,并且我做错了但是我不能在我的生活中找到它,即使在查看了大量示例之后.这是XML片段:

<queue>
<slots>
<slot>
<status>Downloading</status>
<filename>file1</filename>
<size>1 GB</size>
</slot>
<slot>
<status>Downloading</status>
<filename>file2</filename>
<size>2 GB</size>
</slot>
</slots>
</queue>

这是代码

        XDocument xDoc = XDocument.Load(xmlFilePath);

        List<Download> list = new List<Download>();

        foreach (var download in xDoc.Descendants("slots"))
        {
            string filename = download.Element("filename").Value;
            string size = download.Element("size").Value;
            string status = download.Element("status").Value;
            list.Add(new Download { Filename = filename, Size = size, Status = status });              
        }

任何帮助一如既往地非常感谢.

编辑:澄清一下,我得到一个NullReferenceException

string filename = download.Element("filename").Value;

我知道列表视图丢失了,我还没有那么做:)

解决方法:

var list = (from download in xDoc.Descendats("slot")
            select new Download
                    {
                        Filename = (string) download.Element("filename"),
                        Size = (string) download.Element("size"),
                        Status = (string) download.Element("status")
                    }).ToList();

这看起来更好,而且由于你没有说出你的代码究竟出了什么问题,所以我能做的就是这样.

更新:刚测试了这个,它修复了你的异常.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。