Code Snippet: Sort nodes in an Xml Document

Posted at: 7/13/2007 at 4:40 PM by saravana

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>

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:  Categories: .NET
Actions: Email this article Email | Kick it! | DZone it! | Save to del.icio.us | Technorati Links
Post Information: Permanent LinkPermalink | CommentsComments(4) | Comments RSS

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading