C#DataGridView绑定到XML的子集 [英] C# DataGridView binding to subset of XML
本文介绍了C#DataGridView绑定到XML的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要有条件地填充DataGridView。数据来自一个XML文件,例如
I need to populate a DataGridView conditionally. The data comes from one XML file, e.g.
<?xml version="1.0" standalone="yes"?>
<people>
<person>
<name>Bob</name>
<dogs>
<dog><name>Rover</name></dog>
<dog><name>Rex</name></dog>
</dogs>
</person>
<person>
<name>Jim</name>
<dogs>
<dog><name>Duke</name></dog>
<dog><name>Colin</name></dog>
<dog><name>Gnasher</name></dog>
</dogs>
</person>
</people>
如果我使用以下代码,我可以在DataGridView中显示所有的狗 - 但是我需要限制列表给特定人员所有。
If I use the following code I can show all dogs in the DataGridView - but I need to restrict the list to those owned by specific people.
DataSet ds = new DataSet();
ds.ReadXml("data.xml");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "dog";
我该怎么做?
谢谢
Stuart
Thanks Stuart
推荐答案
您可以使用以下代码获取XElements:
You can get the XElements with the following code:
var xml = XDocument.Load(filePath);
var people = xml.Elements("people").Elements("person");
var dogElements = people.Elements("dogs").Elements("dog").Where(p => p.Parent.Parent.Element("name").Value == "Bob");
var dogs = dogElements.Select(d => new {Name = d.Element("name").Value, Owner = d.Parent.Parent.Element("name").Value});
dataGridView1.DataSource = dogs;
dataGridView1.DataMember = "Name";
作为一个例子,我在这里选择了狗的所有者。
Just as an example I selected the owner of the dog as well here.
您必须添加对System.Xml和System.Xml.Linq的引用
You'll have to add a reference to System.Xml and System.Xml.Linq
这篇关于C#DataGridView绑定到XML的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文