ORIGINAL ANSWER
If you change your data structure to multi dimensional arrays/objects can use a recursive function to loop through infinite nesting levels as follows:
var dirs = [{
name: "images",
subdir: [{
name: "vertical"
}, {
name: "horizontal"
}]
}, {
name: "Jquery",
subdir: [{
name: "UI", subdir: [{name:'Nested 1',subdir: [{name:'Nested 2',subdir: [{name:'Nested 3'}]}]}]
}, {
name: "include"
}]
}, {
name: "quickfox"
}];
function createList( array){
var html='<ul>';
$.each( array, function(k, item){
html+='<li>'+item.name;
if( item.subdir){
html+=createList(item.subdir);
}
html+='</li>';
});
html+='</ul>';
return html;
}
$('body').html( createList( dirs))
DEMO: http://jsfiddle.net/AA6yb/1
REVISED ANSWER
Based on updated information that xml already has nesting, issue is how to parse xml not flat array.
Following recursively loops through all directories in xml that are children
. By using find()
you sinply created a flat array since find()
looks for all descendents
function createList($xml) {
var html = '';
$xml.children('directory').each(function () {
var $dir = $(this);
var name= $dir.attr('name');
html += '<li class="dir">' + parseName($dir.attr('name'));
if ($dir.children().length) {
html += '<ul>';
$dir.children('file').each(function () {
html += '<li class="file">' + $(this).attr('path') + '</li>';
});
/* recursively loop through children directories of this directory*/
if( $dir.children('directory').length){
html+=createList($dir);
}
html += '</ul>';
}
});
html += '</li>';
return html;
}
function parseName( name){
if( name.indexOf('/')>-1){
return name.split('/').pop();
}else{
return name;
}
}
$('#directory_list').html(createList($(xmlData)))
HTML
<ul id="directory_list"></ul>