AuthorQuestion
Sorting Xml Elements in C#.Net
Posted on: 16 Mar 2013
Hi i'm having an xml document below like this
<Table>
    <bankname>Canara</bankname>
    <accountid>1</accountid>
    <balance>56789</balance>
  </Table>
  <Table>
    <accountid>0</accountid>
    <bankname>Canara</bankname>
    <balance>56789</balance>
  </Table>
  <Table>
    <accountid>302</accountid>
    <bankname>Canara</bankname>
    <balance>56789</balance>
  </Table>
  <Table>
    <accountid>309</accountid>
    <bankname>Canara</bankname>
    <balance>56789</balance>
  </Table>
  <Table>
    <accountid>310</accountid>
    <bankname>Canara</bankname>
    <balance>56789</balance>
  </Table>
  <Table>
    <accountid>0</accountid>
    <bankname>Canara</bankname>
    <balance>56789</balance>
  </Table>
  <Table>
    <bankname>Canara</bankname>
    <accountid>1</accountid>
    <balance>56789</balance>
  </Table>
  <Table>
    <accountid>302</accountid>
    <bankname>Canara</bankname>
    <balance>56789</balance>
  </Table>
  <Table>
    <accountid>309</accountid>
    <bankname>Canara</bankname>
    <balance>56789</balance>
  </Table>
  <Table>
    <accountid>310</accountid>
    <bankname>Canara</bankname>
    <balance>56789</balance>
  </Table>

I want to order by the document by accountid, and save back

[ + ]
AuthorReply
Re: Sorting Xml Elements in C#.Net
Posted on: 16 Mar 2013  
http://stackoverflow.com/questions/9494275/sorting-of-xml-file-by-xmlelements-innertext
http://www.dotnetcurry.com/ShowArticle.aspx?ID=479

If this post helps you mark it as answer
Thanks

Vulpes
  • 0
  • 0
Re: Sorting Xml Elements in C#.Net
Posted on: 17 Mar 2013  
Try this:

using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
       XElement root = XElement.Load("surendra.xml");
       XElement[] sortedTables = root.Elements("Table").OrderBy(t => (int)t.Element("accountid")).ToArray();
       root.ReplaceAll(sortedTables);
       root.Save("surendra.xml");
    }
}   

Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts