title: Retrieving sub elements of xml using Xdocument
body: <p>I want to parse an XML file like this:</p>
  
  <pre><code> &lt;?xml version="1.0" encoding="utf-8" ?&gt; 
      &lt;database name="myDb"&gt;
        &lt;table name="myTable"&gt;
          &lt;field name="Code" type="int" size="0" identity="true" primarykey="true" description="کد شناسه" reference=""&gt;&lt;/field&gt;
          &lt;field name="Name" type="nvarchar" size="50" identity="false" primarykey="false" description="نام شخص" reference=""&gt;&lt;/field&gt;
        &lt;/table&gt;
        &lt;table name="yourTable"&gt;
          &lt;field name="Code" type="int" size="0" identity="true" primarykey="true" description="کد شناسه" reference=""&gt;&lt;/field&gt;
          &lt;field name="Title" type="nvarchar" size="50" identity="false" primarykey="false" description="نام شخص" reference=""&gt;&lt;/field&gt;
        &lt;/table&gt;
      &lt;/database&gt;
  </code></pre>
  
  <p>The problem is that in my inner foreach it will parse 4 fields instead of 2 fields related to each table. how to change the code to read only the fields for current table?</p>
  
  <pre><code>XDocument xdoc = XDocument.Load("d:\\tables.xml");
          foreach (XNode table in xdoc.Descendants("database").Nodes())
          {
              fields = "";
              tableName = XElement.Parse(table.ToString()).Attribute("name").Value;
              //XElement xE = XElement.Parse(table.ToString());
              //foreach (XElement e in xE.Elements())
              foreach (XNode field in xdoc.Descendants("table").Nodes())
              {
                  fieldName = XElement.Parse(field.ToString()).Attribute("name").Value;
                  type = XElement.Parse(field.ToString()).Attribute("type").Value;
                  size = XElement.Parse(field.ToString()).Attribute("size").Value;
                  identity = XElement.Parse(field.ToString()).Attribute("identity").Value;
                  primarykey = XElement.Parse(field.ToString()).Attribute("primarykey").Value;
                  description = XElement.Parse(field.ToString()).Attribute("description").Value;
                  reference = XElement.Parse(field.ToString()).Attribute("reference").Value;
  
                  if (identity == "true") identity = "identity";
                  if (primarykey == "true") primarykey = "primary key";
  
                  if (isChar(type))
                  {
                      fields += string.Format(fieldCharTemplate, fieldName, type, size);
                  }
                  else
                  {
                      fields += string.Format(fieldNonCharTemplate, fieldName, type, identity,primarykey);
                  }
                  //var y = x.Element("type");
              }
              sql = string.Format(tableTemplate, tableName, fields);
              Response.Write(sql);
          }
  </code></pre>