views:

448

answers:

1

Hi, 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

A: 

Hi,

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

TimothyP
Hmm... haven't played with Linq before. I'll give it go. Thanks!
gingerbbm
Finally I get around to trying this out! But I'm having a problem on the very last line (when setting the DataMember): "Child list for field Name cannot be created."Can you give me a pointer? Thanks in advance!
gingerbbm