Wednesday, August 20, 2008

XML sorting using LINQ to XML

This is a quick method of sorting elements in a XML document using LINQ to XML.

Let's take the following XML document as an example:

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <node>3</node>
  <node>4</node>
  <node>1</node>
  <node>2</node>
  <node>5</node>
</root>

We want to sort nodes in alphabetical order.

Below is the magic code that does this:

XDocument xml = XDocument.Load("XMLFile.xml");
xml.Root.ReplaceNodes(xml.Root.Elements("node").OrderBy(el => el.Value));
xml.Save("XMLFile.xml");
 

This is a very simple example that can be extended to match your needs.

No comments: