title: Convert DataTable into XML hierarchy in C#
body: <p>I have the following DataTable:</p>
  
  <pre><code>A   B   C
  ----------
  A1  B1  C1
  A1  B1  C2
  A1  B1  C3
  A1  B2  C1
  A1  B2  C2
  ----------
  </code></pre>
  
  <p>I tried to convert it using C# to be in XML format like this:</p>
  
  <pre><code>&lt;Data&gt;
      &lt;A&gt;
          &lt;lable&gt;A1&lt;/lable&gt;
          &lt;B&gt;
              &lt;lable&gt;B1&lt;/lable&gt;
              &lt;C&gt;
                  &lt;lable&gt;C1&lt;/lable&gt;
                  &lt;lable&gt;C2&lt;/lable&gt;
                  &lt;lable&gt;C3&lt;/lable&gt;
              &lt;/C&gt;
              &lt;lable&gt;B2&lt;/lable&gt;
              &lt;C&gt;
                  &lt;lable&gt;C1&lt;/lable&gt;
                  &lt;lable&gt;C2&lt;/lable&gt;
              &lt;/C&gt;
          &lt;/B&gt;
      &lt;/A&gt;
  &lt;/Data&gt;
  </code></pre>
  
  <p>I did a deep search and I found something helpful online like <a href="https://stackoverflow.com/questions/5515990/converting-dataset-into-xml-with-nested-elements">this</a>.
  But that one uses relations, and my data is just one table.
  I also tried this C# code:</p>
  
  <pre><code>    using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Windows.Forms;
      using System.Xml.Linq;
      using System.Data.SqlClient;
  
      SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Files;Data Source=localhost");
      con.Open();
      SqlCommand cmd = new SqlCommand("select * from MyTable",con);
      SqlDataAdapter da = new SqlDataAdapter(cmd);
      DataTable DT = new DataTable("Data");
      da.Fill(DT);
      dataGridView1.DataSource = DT;
      con.Close();
      string XML = ToXmlFormat(DT, 0);
      Console.WriteLine(XML);
  
  
  public string ToXmlFormat(this DataTable table, int metaIndex = 0)
  {
      XDocument xdoc = new XDocument(
          new XElement(table.TableName,
              from column in table.Columns.Cast&lt;DataColumn&gt;()
              where column != table.Columns[metaIndex]
              select new XElement(column.ColumnName,
                  from row in table.AsEnumerable()
                  select new XElement(row.Field&lt;string&gt;(metaIndex), row[column])
                  )
              )
          );
  
      return xdoc.ToString();
  }
  </code></pre>
  
  <p>The result was another format which is not nested XML as I explained.
  <a href="https://i.stack.imgur.com/rl7Sc.jpg" rel="nofollow noreferrer">see image</a> </p>
  
  <p>How can I convert my table into the XML format I need?</p>