Sorting MultiLevel XML using Linq C# -


i trying sort xml using linq not working here xml

<hierarchy>   <date>2015/04/01 15:29:10</date>   <folder name="root" id="root">     <file id="fukui_r3_20150327182224.xlsx" />     <file id="borderstest_20150330144902.xlsx" />     <folder name="level-1" id="1427455995512">       <file id="fukui_r3_20150327182224.xlsx" />       <file id="borderstest_20150330144902.xlsx" />       <folder name="zxcf" id="1427869724768">         <file id="fukui_r3_20150327182224.xlsx" />         <file id="borderstest_20150330144902.xlsx" />       </folder>       <folder name="aegh" id="1427869732372">         <file id="fukui_r3_20150327182224.xlsx" />         <file id="borderstest_20150330144902.xlsx" />       </folder>       <folder name="cfgt" id="1427869741718" />     </folder>     <folder name="a-level" id="1427869672074" />     <folder name="g-level" id="1427869682304" />     <folder name="e-level" id="1427869690384" />     <folder name="1-a-level" id="1427869701383" />   </folder> </hierarchy> 

and here code have tried

 xdocument xdoc = xdocument.load(filepath);  foreach (var trans in xdoc.descendants("hierarchy"))  {      trans.replaceall( trans.elements().orderby(x=>x.name.localname));  }   string newxml = xdoc.tostring(); 

but return me same unsorted xml.

rewrite code this:

xdocument xdoc = xdocument.load(filepath); if (xdoc.root != null)     sortxml(xdoc.root); string newxml = xdoc.tostring(); 

and try use method:

private static void sortxml(xcontainer parent) {     var elements = parent.elements()         .orderbydescending(e => e.name.localname)         .thenby(e => (string)e.attribute("name"))         .toarray();      array.foreach(elements, e => e.remove());      foreach (var element in elements) {         parent.add(element);         sortxml(element);     } } 

this code recursively sort hierarchy: files goes after folders , items sorted value of attribute "name".


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -