[英]How to parse hierarchical xml file in javascript
我有以下XML文件
<node title="Home" controller="Home" action="Index">
<node title="Product Listing" controller="Listing" action="Index" >
<node title="Product Detail" controller="Ad" action="Detail" />
</node>
<node title="About Us" controller="AboutUs" action="Index" />
<node title="Contact Us" controller="Contact Us" action="Index" />
<node title="Place Your Order" controller="Order" action="Index" >
<node title="Order Placed" controller="Placed" action="Index" />
</node>
<node title="FAQ" controller="FAQ" action="Index" />
</node>
我想以以下格式解析這些元素
主頁>產品列表>產品詳細信息
主頁>下訂單>下訂單
主頁>聯系我們
主頁>常見問題
主頁>關於我們
我試圖做到這一點,但它不能給出層次化的迭代。
function GetChildNode1(xml) {
$(xml).find('node').each(function (i) {
nodeArray.push($(this).attr('title'));
GetChildNode($(xml).find('node').eq(i));
});
}
我怎樣才能做到這一點 。 XML的這種正確格式是要獲取以下輸出?
保持創建XML的順序。
var string = '<node title="Home" controller="Home" action="Index"><node title="Product Listing" controller="Listing" action="Index" > <node title="Product Detail" controller="Ad" action="Detail" /></node><node title="About Us" controller="AboutUs" action="Index" /><node title="Contact Us" controller="Contact Us" action="Index" /><node title="Place Your Order" controller="Order" action="Index" > <node title="Order Placed" controller="Placed" action="Index" /></node><node title="FAQ" controller="FAQ" action="Index" /></node>'
var $doc = $.parseXML(string);
parse($($doc))
function parse($doc, array) {
array = array || [];
$doc.children('node').each(function () {
var $this = $(this);
array.push($this.attr('title'));
if ($this.is(':has(node)')) {
parse($this, array);
} else {
$('<li />', {
text: array.join()
}).appendTo('ul')
}
array.splice(array.length - 1, 1)
})
}
演示: 小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.