2013-08-29 30 views
0

我有以下XML文件如何解析的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的正確格式以獲得以下輸出

回答

1

保持創建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) 
    }) 
} 

演示:Fiddle

+0

偉大的工作。謝謝 –