I'm having an xml file like
<Root>
<Child val1="1" val2="2"/>
<Child val1="1" val2="3"/>
<Child val1="2" val2="4"/>
</Root>
i need to display the data from the Xml file to a Listview like
(Added A
to index value)
Now i'm using like
1.Stores the data in an XmlNodesList
2.Then iterate through the nodeslist
and add the attribute value to the list开发者_StackOverflow中文版 view
Here i can not use Dictionary<String,String>
as a temporary storage because there exist multiple keys with same name.
Is there any idea to do this using LINQ to XML
.?
Without LINQ:
var doc = new System.Xml.XmlDocument();
doc.LoadXml(xml);
var nodes = doc.SelectNodes("Root/Child");
for (int i = 0; i < nodes.Count; i++)
{
var n = nodes[i];
var index = String.Format("A{0}", i + 1);
var column1 = n.Attributes["val1"].Value;
var column2 = n.Attributes["val1"].Value;
// use variables to add an item to ListView
}
Using LINQ:
using System.Linq;
var doc = new System.Xml.XmlDocument();
doc.LoadXml(xml);
var nodes = doc.SelectNodes("Root/Child");
var arr = nodes
.OfType<XmlNode>()
.ToArray();
var result = arr
.Select(n =>
new
{
ClNo = String.Format("A{0}", Array.IndexOf(arr, n) +1),
Val1 = n.Attributes["val1"].Value,
Val2 = n.Attributes["val2"].Value,
});
ListView list = new ListView();
ListViewItem[] items = result
.Select(r => new ListViewItem(new[] { r.ClNo, r.Val1, r.Val2 })
.ToArray();
list.Items.AddRange(items);
精彩评论