Code Snippet: Sort nodes in an Xml Document

|  Posted: July 13, 2007  |  Categories: General Technical

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>

Author: Saravana Kumar

Saravana Kumar is the Founder and CTO of BizTalk360, an enterprise software that acts as an all-in-one solution for better administration, operation, support and monitoring of Microsoft BizTalk Server environments.

  • sqlpro

    Thank you very much. it was so useful when i needed to do similar thing.

  • Venkateswararao.

    Hi , Thanks . Can you please tell me , which jar you have used.(XmlDocument class…). Thanks in advance

  • Bob

    Doesn’t work if you have two titles that are the same.

One Platform Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

ServiceBus360

Azure service bus

Learn more

Start managing your Azure Service Bus namespaces in minutes

One Platform - Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

One Platform - Operations, Monitoring and Analytics Software
ServiceBus360

Azure service bus

Learn more

Start managing your Azure Service Bus namespaces in minutes

Back to Top