我正在拼命地尝试从一个没有成功的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>
Can you guys please help me out!
Edit:
<!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>
Children
来创建列表。但是要递归地执行此操作,我需要对parents("Parent")
进行操作吗?我的jQuery知识非常有限。抱歉。 - Harsha Venkataramu