Js USES recursion to parse XML

  • 2020-03-30 04:35:22
  • OfStack

XML structure:


<RightMenuItems>
  <Item Code="New" Name=" new " GroupCode="Edit" GroupName=" The editor "/>
  <Item Code="Open" Name=" Open the " GroupCode="Edit" GroupName=" The editor ">
    <item Code="Word" Name="Word The document " GroupCode="CommonDocument" GroupName=" conventional "/>
    <item Code="Excel" Name="Excel The document " GroupCode="CommonDocument" GroupName=" conventional "/>
    <item Code="CustomDocument" Name=" Custom document " GroupCode="CustomDocument" GroupName=" The custom "/>
  </Item>
  <Item Code="Save" Name=" save " GroupCode="Edit" GroupName=" The editor "/>
  <Item Code="Exit" Name=" leave " GroupCode="Exit" GroupName=" leave "/>
</RightMenuItems>

Analytical method:


$(xml).find("RightMenuItems").each(function () {
   this.data = Traversal($(this).children());
 });
var Traversal = function (nodes) {
        var itemList = new Array();
        $.each(nodes, function () {
            var entity = new RightMenuEntity();
            var obj = $(this);
            entity.Code = obj[0].getAttribute("Code");
            entity.Name = obj[0].getAttribute("Name");
            entity.GroupCode = obj[0].getAttribute("GroupCode");
            entity.GroupName = obj[0].getAttribute("GroupName");
            if (obj[0].hasChildNodes()) entity.ChildItems = Traversal(obj.children());
            itemList.push(entity);
        });
        return itemList;
    };


Related articles: