One of my friends asked me how to sort a xml file which is deserialized and put into a treeview.
The xml lookes something like the one shown below:

  <?xml version=”1.0″ encoding=”us-ascii” ?>
– <TreeView>
– <node text=”Topics”>
  <node text=”Animal Health” /> 
– <node text=”Tools”>
– <node text=”Corporate”>
   <node text=”knowledge management” />
   <node text=”Media relations” />
   <node text=”Agency management” />
   <node text=”Messaging” />
   <node text=”Communications planning” />
   <node text=”Newsflow” />

As you can see the xml dosen’t look sorted, So in order to sort it alphabetically, xsl may be the
easiest route. Here’s the transform to sort alphabetically:

<?xml version=”1.0″ encoding=”us-ascii” ?>
<xsl:stylesheet version=”1.0″ xmlns:xsl=”” xmlns:fo=”“>
<xsl:template match=”node”>
                  <xsl:copy-of select=”@*”/>
<xsl:apply-templates select=”node”>
      <xsl:sort select=”@text”/>

Now, we can use XSL Transform to Transform the XML data using the loaded XSLT stylesheet. See the Code Below

string strSortFile = @”C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\sort.xsl”;
string filename = @”C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\BizFocus.xml”;
XmlDocument doc = new XmlDocument();
MemoryStream sstream = new MemoryStream();
// Modify the XML file.
XmlElement root = doc.DocumentElement;
// Create an XPathNavigator to use for the transform.
XPathNavigator nav = root.CreateNavigator();
// Transform the file.
System.Xml.Xsl.XslTransform xtr = new System.Xml.Xsl.XslTransform();
//XmlTextWriter writer = new XmlTextWriter(fileName, null);
XmlTextWriter writer1 = new XmlTextWriter(sstream, null);
xtr.Transform(nav, null, writer1, null);
XmlTextReader reader = null;
sstream.Position = 0;

/*Insert Logic to add node to treeview from XMLTextReader*/
You might get the error ‘Root element is Missing’, but do not worry, it isn’t a problem with the input file or the transform script. The problem is that the XslTransform.Transform function leaves the stream position set to the end of the stream. There’s no root element because the XmlDocument.Load function thinks the stream has a 0 byte length. The fix is to simply set the position to 0.