C# DataGridView binding to subset of XML

大兔子大兔子 提交于 2019-12-11 19:33:11

问题


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>

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";

How do I do this?

Thanks Stuart


回答1:


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.

You'll have to add a reference to System.Xml and System.Xml.Linq



来源:https://stackoverflow.com/questions/1327016/c-sharp-datagridview-binding-to-subset-of-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!