Wednesday, November 7, 2012

Sorting XML in C# alphabetically and by order


Snippet
using System;
using System.Linq;
using System.Xml.Linq;
 
namespace ThrowAwayCSConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = @"<?xml version=""1.0"" encoding=""UTF-8\""?>
                    <websites> 
                        <site language=""Spanish"" name=""Excélsior"" order=""2"">http://www.excelsior.com.mx/</site> 
                        <site language=""Japanese"" name=""TOKYO Web"" order=""3"">http://www.tokyo-np.co.jp/</site>
                        <site language=""Italian"" name=""Corriere della Sera"" order=""1"">http://www.corriere.it/</site>
                        <site language=""Spanish"" name=""SpanishTest1"" order=""4"">www.spanishtest1.com</site> 
                    </websites>";
 
            XDocument xdoc = XDocument.Parse(xml);
            XDocument xNewDoc = new XDocument();
 
            xNewDoc.Add(xdoc.Root);
 
            xNewDoc.Root.RemoveNodes();
            xNewDoc.Root.Add(xdoc.Root.Elements().OrderBy(e => e.Attribute("language").Value));
 
            Console.WriteLine("Before: \r\n{0}", xdoc.ToString());
            Console.WriteLine();
            Console.WriteLine("After: \r\n{0}", xNewDoc.ToString());
            Console.ReadLine();
        }
    }
}
Which produces this output:
Before:
<websites>
 <site language="Spanish" name="Excélsior" order="2">http://www.excelsior.com.mx/</site>
 <site language="Japanese" name="TOKYO Web" order="3">http://www.tokyo-np.co.jp/</site>
 <site language="Italian" name="Corriere della Sera" order="1">http://www.corriere.it/</site>
 <site language="Spanish" name="SpanishTest1" order="4">www.spanishtest1.com</site>
</websites>

After:
<websites>
 <site language="Italian" name="Corriere della Sera" order="1">http://www.corriere.it/</site>
 <site language="Japanese" name="TOKYO Web" order="3">http://www.tokyo-np.co.jp/</site>
 <site language="Spanish" name="Excélsior" order="2">http://www.excelsior.com.mx/</site>
 <site language="Spanish" name="SpanishTest1" order="4">www.spanishtest1.com</site>
</websites>

0 comments:

Post a Comment