title: Populate WPF DataGrid with unknown amount of data from XML
body: <p>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)</p>
  
  <p>The XML is in the format shown below. </p>
  
  <pre><code>&lt;root&gt;
    &lt;Data Name1="Value1" Name2="Value2" ... /&gt;
    &lt;Data Name1="Value1" Name2="Value2" ... /&gt;
    ...
  &lt;/root&gt;
  </code></pre>
  
  <p>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).</p>
  
  <p>I'm struggling to create a backing class for the datagrid to bind to, or to create it all programatically.</p>
  
  <p>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)</p>
  
  <pre><code>List&lt;string&gt; 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);
  }
  </code></pre>
  
  <p>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</p>
  
  <pre><code>foreach (XElement e in xml.Descendants("Data")) {
      //Store values to be added to the datagrid as a new row
      List&lt;string&gt; row = new List&lt;string&gt;();
  
      //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);
  }
  </code></pre>
  
  <p>I'm some of the way there ... but have a datagrid with blank rows (correct number of rows but now data shown).</p>
  
  <p>Any tips/pointers would be appreciated.</p>