如何用javascript解析分层xml文件

How to parse hierarchical xml file in javascript

本文关键字:分层 xml 文件 何用 javascript      更新时间:2023-09-26

我有以下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)
    })
}

演示:Fiddle