Updated to be clear.
Step One: I have a XML file that I want to load into a DatGridView. (Mostly working thanks to Max, but I still have a problem with the XML rollup)
Step Two: Run some code based on user input -- (not part of this solution)
Step Three: Export the DataGridView into a CSV File. (Solved by Max! Thanks Man That was exactly what I was trying to do on that part.)
Using VS 2008 C#
(Created a new project)
Sample from the XML file cars.xml
<?xml version="1.0" encoding="utf-8" ?>
<root>
<car>
<year>2010</year>
<make>Chevy</make>
<model>Surburban</model>
<color-e>Black</color-e>
<color-i>Black</color-i>
<features>
<Engine>8 cylinder</Engine>
<gas>Petrol</gas>
<doors>5</doors>
<miles>12312</miles>
</features>
</car>
<car>
<year>2001</year>
<make>Ford</make>
<model>Excursion</model>
<color-e>Black</color-e>
<color-i>Black</color-i>
<features>
<Engine>10 cylinder</Engine>
<gas>Petrol</gas>
<doors>5</doors>
<miles>90312</miles>
</features>
</car>
<car>
<year>1999</year>
<make>Chevy</make>
<model>corvette</model>
<color-e>Silver</color-e>
<color-i>Black</color-i>
<features>
<Engine>8 cylinder</Engine>
<gas>Petrol</gas>
<doors>3</doors>
<miles>44222</miles>
</features>
</car>
</root>
This is a winform application. It has two button, one textbox, and one datagridview. button one should load the XML data into the datagrid. Then button two should save the data in the datagridview to a CSV file.
Here is the code I have so far to open and load the xml into the datagridview.
namespace carsXML
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var cars = XDocument.Load(@"C:\cars.xml");
var query = from c in cars.Descendants("car")
select new
{
Year = (string)c.Element("year").Value,
Make = (string)c.Element("make").Value,
Model = (string)c.Element("model").Value,
// I needed to step directly into the sub element.
gas = (string)c.Element("features").Element("gas").Value,
doors = (string)c.Element("features").Element("doors").Value,
miles = (string)c.Element("features").Element("miles").Value
};
dataGridView1.DataSource = query.ToList();
}
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.ExportToCSV(@"C:\cars-griddump.csv");
//Added Class Max showed me. This works, I have only tested it on a small
// XML file so far but it seems to work exactly as I wanted.
}
}
}
This gets the elements directly below the car element. When it gets to the feature element the application crashes. (null ref etc.)
So the last part of this before I am done with this little project is to figure out the XML rollup. When the code reads the car elements it gets all of the sub elements that are directly under car. It fails when it gets to the element that has additional sub elements and does not add them to the datagridview.
//Rollup problem fixed. It took me a while though! // Thank you for all of the help!