我正在努力从一个 xml 文件创建一个无序列表,但到目前为止没有运气。我知道如何从 jQuery 处理 xml,但我无法弄清楚如何制作多级无序列表。
这是我到目前为止所取得的成就。
xml文件
<?xml version="1.0" encoding="utf-8"?>
<Parent>Director
<Children>Exe Director1</Children>
<Children>Exe Director2</Children>
<Parent>Exe Director2
<Children>Sub Director 1</Children>
<Children>Sub Director 2</Children>
<Parent>Sub Director 3
<Children>Cameraman 1</Children>
<Children>Cameraman 2</Children>
</Parent>
</Parent>
</Parent>
html文件
<!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: xmlParser
});
});
function xmlParser(xml)
{
$(xml).find("Children").each(function()
{
var text = $(this).text();
});
}
</script>
</head>
<body>
<div id="ListContainer"></div>
</body>
</html>
这是预期的列表
<ul>
<li>Exe Director1</li>
<li>Exe Director2</li>
<ul>
<li>Sub Director 1</li>
<li>Sub Director 2</li>
<ul>
<li>Cameraman 1</li>
<li>Cameraman 2</li>
</ul>
</ul>
</ul>
你们能帮帮我吗!
编辑:
<!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) { xmlParser($(xml)); }
});
});
function xmlParser(xml) {
//alert($(xml).contents());
var $ul = $("<ul>"); // For each Parent, create an <ul>
$(xml).contents().each(function (i, el) {
if (el.nodeType == 3) return true;
if (el.nodeName.toUpperCase() == "CHILDREN")
{
$("<li>").text($(el).text()).appendTo($ul); // Append <li> Children
} else
{
$ul.append(xmlParser($(el))); // Recursively append the other Parent
}
//$("#ListContainer").append($ul);
});
//alert($ul.html());
$("#ListContainer").append($ul);
}
</script>
</head>
<body>
<div id="ListContainer"></div>
</body>
</html>