Update on Reordering Xml Child Nodes with JavaScript
3/16/2007 6:45:06 PM
A couple of days ago I wrote about sorting child nodes using JavaScript. It appears that there was a small mistake and I'd like to rectify that. The code I posted was both correct and incorrect in that it did sort and to an extent it did sort numerically. I found that it wasn't a true numerical sort when I had a parent node that contained 1, 2, 3, 10. The order was actually 10, 1, 2, 3. So the following code is a TRUE numerical sort using JavaScript.
I was going to post this awhile ago but have been extremely busy with work.
function numericalSort(a, b) { return (a - b); }
function
reOrderChildren ( productGroupNode )
{
var node = null;
var path = null;
var products = productGroupNode.getElementsByTagName("product");
var items = new Array(products.length);
for ( p = 0; p < products.length; p++ )
items[p] = products[p].attributes[0].nodeValue;
// numerically sorts array (ASC);
items.sort(numericalSort);
for ( i = 0; i < items.length; i++ )
{
path = "//productGroup/product[@productId='" + items[i] + "']"
// xml is the name of my Xml Data Island <asp:Xml>
node = xml.selectSingleNode(path);
productGroupNode.appendChild(node);
}
}
Easy.
AJAX,
JavaScript,
XML
