Code Snippet: Sort nodes in an Xml Document

Saravana

General

Jul 13, 2007

Scenario: Need to produce a new xml document with particular node list sorted in ascending/descending order

Code:

XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(@”Input.xml”); XmlDocument xmlDocCopy = new XmlDocument(); xmlDocCopy.LoadXml(xmlDoc.OuterXml); xmlDocCopy.SelectSingleNode(“//Links”).RemoveAll(); XmlNode node = xmlDoc.SelectSingleNode(“//Links”); XPathNavigator navigator = node.CreateNavigator(); XPathExpression selectExpression = navigator.Compile(“Link/Title”); selectExpression.AddSort(“.”, XmlSortOrder.Ascending, XmlCaseOrder.None, “”, XmlDataType.Text); XPathNodeIterator nodeIterator = navigator.Select(selectExpression); while (nodeIterator.MoveNext()) { XmlNode linkNode = xmlDoc.SelectSingleNode(“//Link[Title=”” + nodeIterator.Current.Value + “”]”); XmlNode importedLinkNode = xmlDocCopy.ImportNode(linkNode, true); xmlDocCopy.SelectSingleNode(“//Links”).AppendChild(importedLinkNode); } xmlDocCopy.Save(@”Output.xml”);

Input:

<Section> <Links> <Link Id=”1″> <Title>Jupiter Line</Title> <AddedDate>27/05/2007</AddedDate> </Link> <Link Id=”2″> <Title>Alfa Line</Title> <AddedDate>27/05/2007</AddedDate> </Link> <Link Id=”3″> <Title>Zebra Line</Title> <AddedDate>27/05/2007</AddedDate> </Link> <Link Id=”4″> <Title>Copper Line</Title> <AddedDate>27/05/2007</AddedDate> </Link> </Links> </Section>

Output:

<Section> <Links> <Link Id=”2″> <Title>Alfa Line</Title> <AddedDate>27/05/2007</AddedDate> </Link> <Link Id=”4″> <Title>Copper Line</Title> <AddedDate>27/05/2007</AddedDate> </Link> <Link Id=”1″> <Title>Jupiter Line</Title> <AddedDate>27/05/2007</AddedDate> </Link> <Link Id=”3″> <Title>Zebra Line</Title> <AddedDate>27/05/2007</AddedDate> </Link> </Links> </Section>