Shoaib Ijaz
Shoaib Ijaz

Reputation: 5587

How to parse hierarchical xml file in javascript

I have following XML file

<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>

i want to parse these element in following formats

Home > Product Listing > Product Detail

Home > Place Your Order > Order Placed

Home > Contact Us

Home > FAQ

Home > About Us

I have tried to do this but it cannot give hierarchical iteration.

  function GetChildNode1(xml) {
        $(xml).find('node').each(function (i) {
            nodeArray.push($(this).attr('title'));
            GetChildNode($(xml).find('node').eq(i));
        });
    }

How can i do this . is this correct format of xml to get following output

Upvotes: 0

Views: 516

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

With maintaining the order in which the XML is created.

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)
    })
}

Demo: Fiddle

Upvotes: 1

Related Questions