title: Sorting all the elements in a XDocument
body: <p>I have a XDocument where I'd like to sort all of the elements alphabetically. Here's a simplified version of the structure:</p>
  
  <pre><code>&lt;Config&gt;
   &lt;Server&gt;
      &lt;Id&gt;svr1&lt;/Id&gt;
      &lt;Routing&gt;
          &lt;RoutingNodeName&gt;route1&lt;/RoutingNodeName&gt;
          &lt;Subscription&gt;
              &lt;Id&gt;1&lt;/Id&gt;
          &lt;/Subscription&gt;
          &lt;RoutingParameters id="Routing1"&gt;
              &lt;Timeout&gt;7200&lt;/Timeout&gt;
          &lt;/RoutingParameters&gt;
      &lt;/Routing&gt;
      &lt;Storage&gt;
              &lt;Physical&gt;HD1&lt;/Physical&gt;
      &lt;/Storage&gt;
   &lt;/Server&gt;
   &lt;Applications&gt;
      &lt;Services&gt;
          &lt;Local&gt;&lt;/Local&gt;
      &lt;/Services&gt;
   &lt;/Applications&gt;
  &lt;/Config&gt;
  </code></pre>
  
  <p>I'm wanting to sort the elements in this documents at all levels, so far I'm able to sort it like so:</p>
  
  <pre><code>private static XDocument Sort(XDocument file)
  {
      return new XDocument(
          new XElement(file.Root.Name,
              from el in file.Root.Elements()
              orderby el.Name.ToString()
              select el));
  }
  </code></pre>
  
  <p>Which produces:</p>
  
  <pre><code>&lt;Config&gt;
  &lt;Applications&gt;
    &lt;Services&gt;
      &lt;Local&gt;&lt;/Local&gt;
    &lt;/Services&gt;
  &lt;/Applications&gt;
  &lt;Server&gt;
    &lt;Id&gt;svr1&lt;/Id&gt;
    &lt;Routing&gt;
      &lt;RoutingNodeName&gt;route1&lt;/RoutingNodeName&gt;
      &lt;Subscription&gt;
        &lt;Id&gt;1&lt;/Id&gt;
      &lt;/Subscription&gt;
      &lt;RoutingParameters id="Routing1"&gt;
        &lt;Timeout&gt;7200&lt;/Timeout&gt;
      &lt;/RoutingParameters&gt;
    &lt;/Routing&gt;
    &lt;Storage&gt;
      &lt;Physical&gt;HD1&lt;/Physical&gt;
    &lt;/Storage&gt;
  &lt;/Server&gt;
  &lt;/Config&gt;
  </code></pre>
  
  <p>I'd like to be able to sort all of the children elements in the same way (through a recursive function ideally). Any ideas how I can get this going with LINQ?</p>
  
  <p>Thanks for any ideas.</p>