简体   繁体   English

C#DataGridView绑定到XML的子集

[英]C# DataGridView binding to subset of XML

I need to populate a DataGridView conditionally. 我需要有条件地填充DataGridView。 The data comes from one XML file, eg 数据来自一个XML文件,例如

<?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>

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. 如果使用以下代码,则可以显示DataGridView中的所有狗-但我需要将列表限制为特定人员拥有的狗。

DataSet ds = new DataSet();
ds.ReadXml("data.xml");

dataGridView1.DataSource = ds;
dataGridView1.DataMember = "dog";

How do I do this? 我该怎么做呢?

Thanks Stuart 谢谢斯图尔特

You can get the XElements with the following code: 您可以使用以下代码获取XElement:

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. 举个例子,我在这里也选择了狗的主人。

You'll have to add a reference to System.Xml and System.Xml.Linq 您必须添加对System.Xml和System.Xml.Linq的引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM