How can I sort selected elements into a nodelist?

I have a XML document already loaded in memory.  I would like to select certain elements from the document, sort them, and end up with them in a nodelist. 

Is that possible   And if so, can someone point to some documentation/examples on how to do it

My initial thought was to use the following XSLT on the XmlDocument:

    <xsl:apply-templates select="//section[@key='books']/book">
        <xsl:sort select="@isbn" />
    </xsl:apply-templates>

First problem is that the XSLT was being created dynamically, not read from a file.  Yet, I don't see a way of populating XslTransform with the string.

The second issue is that Transform returns a XmlReader while I need a nodelist.  While I probably can extract a nodelist from the resulting output, I was wondering if there's a simplier/cleaner solution

Or, is there a built-in way of just sorting a XmlNodeList that I'm not aware of

TIA,

Richard



Answer this question

How can I sort selected elements into a nodelist?

  • ilife

    Thanks for the reply.

    Richard

  • wsun

    You can have a sorted selection from an XPathNavigator using XPathExpression.AddSort() method. And to get an XPathNavigator out of XmlDocument use XmlDocument.CreateNavigator() method.
    This gives you XPathNodeIterator, not XmlNodeList. You can iterate it and get every XmlNode using IHasXmlNode interface:

    while (nodes.MoveNext()) {
      XmlNode node = ((IHasXmlNode)nodes.Current).GetNode();
    }


  • Cheng Du

    Excellent solution.

  • How can I sort selected elements into a nodelist?