我正在尝试使用 jquery 将嵌套的 xml 文档转换为无序列表。xml 文档是
<?xml version="1.0" encoding="utf-8"?>
<Parent>
<name>Director</name>
<Children>Exe Director1</Children>
<Children>Exe Director2</Children>
<Parent>
<name>Exe Director3</name>
<Children>Sub Director 1</Children>
<Children>Sub Director 2</Children>
<Parent>
<name>Sub Director 3</name>
<Children>Cameraman 1</Children>
<Children>Cameraman 2</Children>
</Parent>
</Parent>
</Parent>
预期输出:
<ul>
<li>Director
<ul>
<li>Exe Director 1</li>
<li>Exe Director 2</li>
<li>Exe Director 3
<ul>
<li>Sub Director 1</li>
<li>Sub Director 2</li>
<li>Sub Director 3
<ul>
<li>Cameraman 1</li>
<li>Cameraman 2</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
我得到的输出。
<ul>
<li>Director</li>
<ul>
<li>Exe Director1</li>
<li>Exe Director2</li>
<li>Exe Director3</li>
<ul>
<li>Sub Director 1</li>
<li>Sub Director 2</li>
<li>Sub Director 3</li>
<ul>
<li>Cameraman 1</li>
<li>Cameraman 2</li>
</ul>
</ul>
</ul>
</ul>
如您所见,子代不是在父代内部li
而是在其外部创建的最新版本的代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var levels;
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: function (xml) {
var $ul = xmlParser(xml, $('#ListContainer'));
}
});
});
function xmlParser(xml,ul) {
$(xml).contents().each(function (i, el)
{
if (el.nodeName.toUpperCase() == "CHILDREN")
{
$("<li>").text($(el).text()).appendTo($('ul:last')); // Append <li> Children
} else if (el.nodeName.toUpperCase() == "NAME")
{
$('<li>').text($(el).text()).appendTo(ul);
$('<ul>').insertAfter($("li:last"));
}
else if (el.nodeName.toUpperCase() == "PARENT")
{
if($('ul').length == 0)
{
ul = ul.append('<ul>');
}
ul.append(xmlParser($(el),$("ul:last") )); // Recursively append the other Parent
}
});
return ul;
}
</script>
</head>
<body>
<div id="ListContainer"></div>
</body>
</html>
我对这段代码感到头疼。你们能帮我解决可能出现的问题吗!
谢谢