Reputation: 15
I have created a WinForm
in C#, now I want to show the selected data of my XML file to show in DataGridView
. I found some links that helped with showing the selected elements in the DataGridView
but it's not showing as it should be.
Following is my XML file
<?xml version="1.0" encoding="utf-8"?>
<root>
<Vehicle>
<Number_Plate>PHZ-888</Number_Plate>
<Make>Honda</Make>
<Model>City</Model>
<Year>2008</Year>
</Vehicle>
<Vehicle>
<Number_Plate>VGQ-141</Number_Plate>
<Make>Suzuki</Make>
<Model>Mehran</Model>
<Year>2001</Year>
</Vehicle>
<Vehicle>
<Number_Plate>VZH-403</Number_Plate>
<Make>Audi</Make>
<Model>A7</Model>
<Year>2008</Year>
</Vehicle>
<Vehicle>
<Number_Plate>BCH-184</Number_Plate>
<Make>Honda</Make>
<Model>Accord CL9</Model>
<Year>2007</Year>
</Vehicle>
</root>
Here is the query I'm trying to use to get specific elements:
XDocument xdoc = XDocument.Load("vehicle20.xml");
var query = from key in xdoc.Descendants("Vehicle")
where key != null && (key.Element("Make").Value == makelist)
select key.Value;
dataGridView1.DataSource = query.ToList();
makelist
is how I am passing the car model to search for, such as "Honda".
And After querying it shows this:
But I want to display with all the descendants of specified vehicle elements, like for Audi to show only Audi data, this way:
Upvotes: 1
Views: 1001
Reputation: 125292
As an option you can load xml data to a DataSet
and show it in DataGridView
simply this way:
var ds = new DataSet();
ds.ReadXml("path to the xml file");
dataGridView1.DataSource = ds.Tables[0]; //ds.Tables[Vehicle]
Then to filter data and show some specific rows, you can apply filter this way:
ds.Tables[0].DefaultView.RowFilter = "Make='Honda'";
Upvotes: 1
Reputation: 105
The result is expected, because your are selecting Key.value
. If you want to get the desired display, you should wrap your result in an object:
var query = from key in xdoc.Descendants("Vehicle") where key != null && (key.Element("Make").Value == "Honda") select new { Make = key.Element("Make").Value, Model = key.Element("Model").Value };
Upvotes: 1