title: Convert dynamic DataTable to XML
body: <p>I have a stored procedure that returns variable data from an EAV database and want to export the data as an XML.</p>
  
  <p>DataTable columns: </p>
  
  <pre><code>group varchar
  attribute varchar
  value varchar
  </code></pre>
  
  <p>Datatable Example:</p>
  
  <pre><code>group       attribute      value
  General     Name           Big Bird
  BodyType    Color          Yellow
  BodyType    Height         200
  General     Age            5
  </code></pre>
  
  <p>Desired XML:</p>
  
  <pre><code>&lt;RootTag&gt;
     &lt;General&gt;
       &lt;Name&gt;Big Bird&lt;/Name&gt;
       &lt;Age&gt;5&lt;/Age&gt;
     &lt;/General
     &lt;BodyType&gt;
       &lt;Color&gt;Yellow&lt;/Color&gt;
       &lt;Height&gt;200&lt;/Height&gt;
     &lt;/BodyType&gt;
  &lt;/RootTag&gt;
  </code></pre>
  
  <p>If I do a DataTable.WriteXml I get:</p>
  
  <pre><code>&lt;Item&gt;
    &lt;group&gt;General&lt;/group&gt;
    &lt;attribute&gt;Name&lt;/attribute&gt;
    &lt;value&gt;Big Bird&lt;/value&gt;
  &lt;/Item&gt;
  &lt;Item&gt;
    &lt;group&gt;BodyType&lt;/group&gt;
    &lt;attribute&gt;Color&lt;/attribute&gt;
    &lt;value&gt;Yellow&lt;/value&gt;
  &lt;/Item&gt;
  ...
  </code></pre>
  
  <p>I am currently building a type dynamically at run-time with reflection and serializing with that type.  I'm thinking there has to be a better way.</p>
  
  <p>EDIT: DataTable.WriteXml sample</p>
  
  <pre><code>public static string BuildFullXML(DataTable OrderData, string OutPath)
  {
      if (!Directory.Exists(OutPath)) { Directory.CreateDirectory(OutPath); }
      OutPath += DateTime.Now.Ticks + ".xml";
  
      OrderData.TableName = "Item";
  
      using (TextWriter TW = File.CreateText(OutPath))
      {
          OrderData.WriteXml(TW);
          TW.Close();
      }
  
      return path;
  }
  </code></pre>