简体   繁体   中英

Creating html ul li from nested xml element using jquery

I have an xml as -

<item name="a">
   <item name="d">
      <item name="g">
          ...
      </item>
      ...
   </item>
   <item name="e"></item>
   <item name="f"></item>
   ...
</item>
<item name="b"></item>
<item name="c"></item>

I want to create a ul li tree structure of this xml as

a [node]
 d [node]
  g [node]
  .
  .
  .
 e [node]
 f [node]
 .
 .
b [node]
c [node]

I guess I would need to make a infinte loop, but finding it difficult to do it in jquery. My jquery would resemble somewhat like this -

function createNestedTree(obj) {
  $("#tree").append("<ul></ul>");
  $(obj).children("item").each(function(){
    $("#tree ul").append("<li>"+$(this).attr("name")+"</li><ul id="+$(this).attr("name")+"level></ul>");
    $(this).children("item").each(function(){
       //logic here
    });
  });
}

Any help is greatly appreciated.

Does this work for you ?

 function jumpdown (obj) {
   if (obj.hasChildNodes()) {
     var nextlevel = "<li>"+$(obj).attr("name")+"</li><ul id='"+$(obj).attr("name")+"level'>";
     for (var i=0 ; i<obj.chilNodes.length, i++)
     {
       nextlevel = nextlevel + jumpdown(obj.chilNodes[i]);
     }
     nextlevel = nextlevel + "</ul>";
     return nextlevel;
   }
   else return "<li>"+$(obj).attr("name")+"</li>";
 }

 jumpdown(mydocumentxml);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM