2013-04-09 83 views
0
<script>   
$(document).ready(function(){ 
      var xml = "<root> \ 
         <method name='A'> \ 
         <childcall name='B'></childcall> \ 
         <childcall name='C'></childcall> \ 
         </method> \ 
         <method name='B'> \ 
         <childcall name='D'></childcall> \ 
         </method> \ 
         <method name='C'> \ 
         <childcall name='D'></childcall> \ 
         <childcall name='E'></childcall> \ 
         </method> \ 
         </root>"; 

      var data = $.parseXML(xml); 
      console.log(data); 
      $(data).find('method').each(function(){ 
       var name = $(this).attr('name'); 
       $('<div class="items"></div>').html('<a href="'+name+'">'+name+'</a>').appendTo('#page-wrap'); 

      }); 
     }); 

    </script> 
</head> 
<body> 
    <div id="page-wrap"></div> 
</body> 
</html> 

此代碼爲父方法標記輸出A B C。所需的輸出是A B C B D C D E 如何遞歸遍歷子節點以獲取所需的輸出?這是深度優先搜索嗎?使用JQuery遞歸解析XML

回答

1

試試這個:

// Loop through the parent items 
$(data).find('method').each(function() { 
    var name = $(this).attr('name'); 
    $('<div class="items"></div>').html('<a href="' + name + '">' + name + '</a>').appendTo('#page-wrap'); 

    // Loop through the child items 
    $(this).find('childcall').each(function() { 
     name = $(this).attr('name'); 
     $('<div class="items"></div>').html('<a href="' + name + '">' + name + '</a>').appendTo('#page-wrap'); 
    }); 
}); 
0

如果有人有興趣建立所有嵌套節點,更新的代碼如下

$(xml).find('thymeSiteMap').each(function() { 
 
    var name = $(this).attr('en'); 
 
    var id= $(this).attr('id'); 
 
    console.log(id); 
 
    $('<div class="items shift" id="'+id+'"></div>').html('<a href="' + name + '">' + name + '</a>').appendTo('#page-wrap'); 
 

 
    // Loop through the child items 
 
    $(this).find('thymeNode').each(function() { 
 
    \t 
 
    \t var parent = $(this).parent().attr('id'); 
 
    \t console.log("me "+$(this).attr('id') +" my parent "+parent); 
 
     name = $(this).attr('en'); 
 
     var divname="div#"+parent+".items"; 
 
     console.log(divname); 
 
     var id= $(this).attr('id'); 
 
    
 
     $('<div class="items shift" id="'+id+'"></div>').html('<a href="' + name + '">' + name + '</a>').appendTo(divname); 
 
    });
<!doctype html> 
 
    <html > 
 
     <head> 
 
     <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> 
 
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> 
 
     
 
     <style> 
 
     
 
     .shift{ 
 
     \t 
 
     \t position:relative; 
 
     \t left:20px; 
 
     } 
 
     
 
     
 
     </style> 
 
     </head> 
 
     <body> 
 
     <div id="page-wrap" class="shift"></div> 
 
    
 
     </body> 
 
    </html>