2013-08-29 31 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

伟大的工作。谢谢 –