Quantcast
Channel: XML, System.Xml, MSXML and XmlLite forum
Viewing all articles
Browse latest Browse all 935

How to Sort XDocument Content by Node Name

$
0
0

Hi folks,

Please can you help with sorting elements in an xml file...I'm new to LINQ to XML.

I have the following file:

<my_elem>   <Toms_elem>      <Kates_elem />      <Als_elem />      <your_elem />      <another_elem>         <some_elem>            <num3>13</num3>            <num1>14</num1>            <num2>15</num2>         </some_elem>      </another_elem>      <sams_elem>         <item_elem>            <elem6>1</elem6>            <elem4>2</elem4>            <elem2>3</elem2>            <elem1>4</elem1>         </item_elem>      </sams_elem>   </Toms_elem>   <dudes_elem>      <Kates_elem />      <Als_elem />      <dummy_elem>         <c_elem>cde</c_elem>         <a_elem>abc</a_elem>      </dummy_elem>   </dudes_elem></my_elem>

I need all elements sorted by name, as follows:

<my_elem>   <dudes_elem>      <Als_elem />      <dummy_elem>         <a_elem>abc</a_elem>         <c_elem>cde</c_elem>      </dummy_elem>      <Kates_elem />   </dudes_elem>   <Toms_elem>      <Als_elem />      <another_elem>         <some_elem>            <num1>14</num1>            <num2>15</num2>            <num3>13</num3>         </some_elem>      </another_elem>      <Kates_elem />      <sams_elem>         <item_elem>            <elem1>4</elem1>            <elem2>3</elem2>            <elem4>2</elem4>            <elem6>1</elem6>         </item_elem>      </sams_elem>      <your_elem />   </Toms_elem></my_elem>

I thought I could do it with LINQ to xml using something like this:

XDocument xmldoc = XDocument.Load ("update.xml");
IEnumerable<XElement> elems = from el in xmldoc.Elements ()                              orderby el.Name                              select el;
xmldoc.ReplaceNodes (elems);

but this returns the same exact doc as the original. What am I doing wrong? Please help.

Many Thanks.

Peter



Viewing all articles
Browse latest Browse all 935

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>