2

I need some help with JavaScript.I am working with XML so i need on which i am implementing JavaScript, and i would like to do sorting of the elements node name. Please see the following figure which will make you clear what i am talking about. Please i want the code with JavaScript not Jquery.

Live Fiddle


UnSorted:                                   Sorted:

bookstore                                   bookstore
  xbook                                         abook
     title                                         author
     author                                        price
     year                                          title
     price                                         year
  cbook                                        cbook
  gbook                                        gbook
  abook                                        xbook    

function generate(node) {
    if (node.nodeType != 1) return "";
    var html = "<li>" + node.nodeName;
    var htmlForChildNodes = "";
    for (var i = 0; i < node.childNodes.length; i++) {
        htmlForChildNodes += generate(node.childNodes[i]);
    }
    if (htmlForChildNodes) {
        html += "<ul>" + htmlForChildNodes + "</ul>";
    }
    html += "</li>";
    return html;
}

Thank you

user3350333
  • 69
  • 2
  • 8

1 Answers1

1

You should parse the xml document and put it into a javascript array of objects. Those are easily sortable.

So instead of calling generate(xmlDoc.documentElement) and have it return html straight from the xml you should add a parse(xmlDoc.documentElement) function that returns an array of arrays. After that change your generate() function to take an object with a children property that is an array instead of the original xml dom.

Parse should look something like this:

function parse(node) {
    if (node.nodeType != 1) return null;
    var result = {name: node.nodeName};
    var children = [];
    for (var i = 0; i < node.childNodes.length; i++) {
        var child = parse(node.childNodes[i]);
        if (child)
        {
            children.push(child);
        }
    }
    result.children = children;
    return result;
}

Now you can sort the arrays with children by creating your own comparator function.

After sorting you call the (changed) generate() function that will iterate over the objects/arrays to produce the html.

Here is a fiddle. I've left the changes of the generate() function to you. (Use your browser console to inspect the generated data structure)

Community
  • 1
  • 1
Simon Groenewolt
  • 10,607
  • 1
  • 36
  • 64