I'm trying to read all of the attributes in the 'Data' elements from an xml file and display them in a DataGrid (WPF, .Net 4.0)
The XML is in the format shown below.
<root>
<Data Name1="Value1" Name2="Value2" ... />
<Data Name1="Value1" Name2="Value2" ... />
...
</root>
I have no idea of the attribute names used (e.g. Name1, Name2, Foo etc.) or the number of attributes there are in each element (potentially different number of attributes for each element). Each new element should be displayed on a new row, and each attribute corresponds to a column (if it doesn't exist for that row display null).
I'm struggling to create a backing class for the datagrid to bind to, or to create it all programatically.
My current attempt is to create a set of text columns (given a list of the column names to use based on what I've extracted from the xml file)
List<string> dataTags = ...; //get list of attributes to use from xml
foreach (string d in dataTags) {
DataGridTextColumn col = new DataGridTextColumn();
col.Header = d;
dataGrid.Columns.Add(col);
}
I then iterate through each attribute and add it to a list (to represent the row to display in the datagrid) if the attribute name matches one of the header values
foreach (XElement e in xml.Descendants("Data")) {
//Store values to be added to the datagrid as a new row
List<string> row = new List<string>();
//Only add data where the attribute name matches one of the 'dataTags' we are given.
foreach(string d in dataTags) {
foreach (XAttribute a in e.Attributes()) {
if (d.Equals(a.Name.ToString())) {
row.Add(a.Value);
break;
}
}
}
//Add new row to the datagrid
dgData.Items.Add(row);
}
I'm some of the way there ... but have a datagrid with blank rows (correct number of rows but now data shown).
Any tips/pointers would be appreciated.