2

I have a large javascript object converted from XML. It has hierarchy, xml attributes (properties defined by an @attributename symbol) and xml values (properties defined by an #text symbol). So the following:

<parentnode length="5">
    <childnode length="22" depth="45">This is a child node</childnode>
</parentnode>

creates an object that looks like this:

parentnode {
    @length: "22"
    childnode {
        @depth: "45",
        @text: "This is a child node"
    }
}

and I want to create an HTML list that looks like this:

<ul>
    <li data-length="22">parentnode
       <ul>
           <li data-depth="45">childnode: This is a child node</li>
        </ul>
    </li>
</ul>

I've tried various solutions, but none of them work for objects nested in objects with various data types.

2
  • did you check this already? stackoverflow.com/questions/5127554/parse-xml-to-ul it looks like you just need to parse an xml object to an ordered list, don't you?.. Commented Aug 2, 2017 at 10:10
  • @briosheje Yes, but I'm looking for a different layout. That solution focuses on arrays of urls for a menu system. Commented Aug 2, 2017 at 10:30

1 Answer 1

5

Put together a simple solution. Maybe this will help someone else:

function createHtmlList(obj){
    var output = "";
    Object.keys(obj).forEach(function(k) {
        if (typeof obj[k] == "object" && obj[k] !== null){
            output += "<li>" + htmlSpecialChars(k) + "<ul>";
            output += createHtmlList(obj[k]);
            output += "</ul></li>";
        } else {
            output += "<li>" + k + " : " + obj[k] + "</li>"; 
        }
    });
    return output;
}
Sign up to request clarification or add additional context in comments.

3 Comments

@TheCarver my solution is in Javascript.
My apologies, I commented on the wrong answer!! I couldn't reverse my downvote unless changes were made to your answer, so I just neatened up the formatted code and upvoted you again :/
I don't have htmlSpecialChars(). Ended up using entities.encode(k) instead

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.