Normally, one can do it through a simple xsl transformation. The central piece is an identity transformation whereas the template matching element node is slightly modified for the purpose of the required sorting. This is the typical look of it.
If you've not much of an idea of xslt, read up its general way of thinking in terms of templates or functional programming and its general settings, and apply the above. You can of course even integrate xslt with your existing document object inside your programming code as you said you have it already.