js中递归解析xml

时间:2024-05-23 13:04:32

xml结构:

<RightMenuItems>
  <Item Code="New" Name="新建" GroupCode="Edit" GroupName="编辑"/>
  <Item Code="Open" Name="打开" GroupCode="Edit" GroupName="编辑">
    <item Code="Word" Name="Word文档" GroupCode="CommonDocument" GroupName="常规"/>
    <item Code="Excel" Name="Excel文档" GroupCode="CommonDocument" GroupName="常规"/>
    <item Code="CustomDocument" Name="自定义文档" GroupCode="CustomDocument" GroupName="自定义"/>
  </Item>
  <Item Code="Save" Name="保存" GroupCode="Edit" GroupName="编辑"/>
  <Item Code="Exit" Name="离开" GroupCode="Exit" GroupName="离开"/>
</RightMenuItems>

解析方法:

$(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;
    };