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>

Tags:  Categories: .NET
Actions: Email this article Email | Kick it! | DZone it! | Save to del.icio.us | Technorati Links
Post Information: Permanent LinkPermalink | CommentsComments(11) | Comments RSS

Comments

Friday, July 27, 2007 4:16 PM
elgoYa
For order by attribute using @nameattribute.

Example:

selectExpression.AddSort("@order", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number);
Thursday, August 02, 2007 9:29 PM
Anonymous
Anonymous
Good approach.  But this may fail if you have two nodes with Same title.  The above method works only for nodes with distinct Titles.

-Sai
Tuesday, August 07, 2007 1:10 PM
Anonymous
Anonymous
while (myNodeIterator.MoveNext())
            {
            XmlNode  newNode = ((IHasXmlNode)myNodeIterator.Current).GetNode().ParentNode   ;
            myXmlNode.AppendChild(newNode);
            }
            myXmlDoc.Save("filename.xml");


Another way to sort and update  xml file.
Wednesday, February 20, 2008 9:49 AM
AsWaM
Nice but a bit complicated in my opinion Wink
What about a mapping with inline XSLT script?

(xsl:for-each select="Order")
(xsl:sort select="Date" data-type="text" order="ascending"/)
(xsl:copy-of select="." /)
(/xsl:for-each)


I use it often and it is fine.

Of course replace brackets with greater than sign....
Wednesday, July 14, 2010 3:36 PM
tmobile customer service number
This is exactly what i needed. Produce a new xml document with particular node list sorted in
ascending/descending order. i have been working on my college project and was searching for this bit of code.OMG i just can't believe i have found it. How should i thank you guys for coming up with such incredible stuff.the best thing about all these u have in store for us what we need at the moment. The code is great needless to say works wonders. thanks to you i feel so relieved now. I have just subscribed you  and i'm going to recommend this to my friends as well. Great Stuff..!! Keep up the good work.
Thursday, August 05, 2010 1:45 AM
Seattle Limo
If you think of vision and mission as an organization's head and heart, the values it holds are its soul.
Saturday, August 07, 2010 3:52 PM
Nude Cam
Hi  blog im from manchester im thinking of doing a manchester solicitors blog, thanks for your info i got some useful tips for my blog.
Saturday, August 07, 2010 4:19 PM
Sex Cam
Your post really made me think, have you any further reading you would recommend?
Thursday, August 19, 2010 9:13 AM
Document Binders
I have also a doubt that it will only work  for nodes with distinct titles but i am not sure about it.
Wednesday, August 25, 2010 4:46 PM
Forex Signal Service
Definitely agree with what you stated. Your explanation was certainly the easiest to understand. I inform you, I usually get irked when folks discuss issues which they plainly don't know about. You managed to strike the nail right on the head and explained out everything without having complication. Maybe, people can take a signal. Will likely be back to get more. Thanks
Wednesday, September 01, 2010 5:14 AM
send flowers
I really liked your article. Keep up the good work.
I love flowers...I am also interested to send flowers all over the world....

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading