我有一个类似ListView
的控件
我需要将此 ListView 中的数据存储到 Xml 文件中。
所以xml文件会是这样的
<root>
<Child Name ="A1" val1="1" val2="0"/>
<Child Name ="A2" val1="1" val2="2"/>
<Child Name ="A3" val1="1" val2="3"/>
<Child Name ="A4" val1="1" val2="4"/>
<Child Name ="A5" val1="1" val2="5"/>
<Child Name ="A6" val1="6" val2="0"/>
<Child Name ="A7" val1="7" val2="0"/>
</root>
如果数据存储在一些 List
或 Dictionary
中,那么我知道使用 XML to LINQ 来做到这一点
但是我如何从 ListView 执行此操作
XDocument XD=new XDocument(new XElement("root",........// what i have to do here.......
请帮我做这个...
提前致谢
最佳答案
您可以查询 ListView 子项及其列标题:
XDocument document = new XDocument(new XElement("root",
from item in yourListView.Items.Cast<ListViewItem>()
select new XElement("Child",
item.SubItems.Cast<ListViewSubItem>()
.Select((subitem, i) => new XAttribute(
i == 0 ? "Name" : yourListView.Columns[i].Text.ToLower(),
subItem.Text)))));
编辑:因为 ListViewItemCollection 都不是也不ListViewSubItemCollection支持开箱即用的查询运算符,我们需要调用 Cast<T>()
能够使用它们。
关于c# - 如何从 C# 中的 ListView 写入 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4067027/