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

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Sir i am confused, need a live fiddle
There are comments in the fiddle that explain what still needs to be done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.