从XML文件填充ListView [英] Populate ListView from XML file
问题描述
我有以下示例XML文件,我需要从该文件中填充ListView.我已经玩了几个小时,但是我不知道最好的解决方法.我想使用Linq来实现这一目标,但我的知识有些缺乏.这是一个Winforms c#项目.
I have the following sample XML file from which i need to poplutate a ListView. I've been playing for hours but I don't know the best way to go about it. I want to use Linq to achieve this but my knowledge is somewhat lacking. It is a Winforms c# project.
<DMs>
<dataModule>
<DMC>11111</DMC>
<techName>Test Techname 1</techName>
<infoName>info 1</infoName>
<status>complete</status>
<notes>Note 1</notes>
</dataModule>
<dataModule>
<DMC>22222</DMC>
<techName>Test Techname 2</techName>
<infoName>info 2</infoName>
<status>in work</status>
<notes>Note 2</notes>
</dataModule>
<dataModule>
<DMC>33333</DMC>
<techName>Test Techname 3</techName>
<infoName>info 3</infoName>
<status>QA required</status>
<notes>Note 3</notes>
</dataModule>
</DMs>
我有以下非常基本的代码,可以用DMC元素文本成功填充listview的第一列,但是我需要同级元素(techName,infoname,status和notes)来填充listview的其他列. /p>
I have the following very basic code which successfully populates the first column of the listview with the DMC element text, but i need the sibling elements (techName, infoname, status and notes) to populate the other columns of the listview.
XDocument doc = XDocument.Load(CSDBpath + projectName + "\\Data.xml");
var DMCs = from item in doc.Descendants("dataModule")
select item.Element("DMC").Value;
foreach (var dmc in DMCs)
{
ListViewItem item = new ListViewItem(dmc);
listView1.Items.Add(item);
}
推荐答案
您需要在ListView
中添加适当的列,并填充每个项目的子项:
You need to add appropriate columns to the ListView
, and the fill the subitems for each item:
// Add required columns
listView1.Columns.Add("DMC");
listView1.Columns.Add("Tech Name");
listView1.Columns.Add("Info Name");
listView1.Columns.Add("Status");
listView1.Columns.Add("Notes");
XDocument doc = XDocument.Load(CSDBpath + projectName + "\\Data.xml");
foreach (var dm in doc.Descendants("dataModule"))
{
ListViewItem item = new ListViewItem( new string[]
{
dm.Element("DMC").Value,
dm.Element("techName").Value,
dm.Element("infoName").Value,
dm.Element("status").Value,
dm.Element("notes").Value
});
listView1.Items.Add(item);
}
这篇关于从XML文件填充ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!