使用jQuery将XML转换为javascript数组

我是XML和AJAX的新手,我只是Javascript和jQuery的新手。 在我设计我们的网站的其他工作职责。 截止日期非常接近,我能想到的唯一方法是使用AJAX。 我有一个充满XML对象的文档,比如这个重复:

     

我想创建一个包含所有元素及其子元素的数组。 我已经阅读了几个小时的AJAX jQuery教程,甚至不知道从哪里开始,因为他们都假设一定程度的javascript熟练程度。 如果有人能告诉我循环所有元素并将他们的孩子放入arrays的最简单方法,我会很感激。

使用jQuery, $.ajax()你的XML文件,并成功传递检索到的数据,如:

  var tmpSubject, tmpDate, tmpThumb; $.ajax({ url: '/your_file.xml', type: 'GET', dataType: 'xml', success: function(returnedXMLResponse){ $('item', returnedXMLResponse).each(function(){ tmpSubject = $('subject', this).text(); tmpDate = $('date', this).text(); tmpThumb = $('thumb', this).text(); //Here you can do anything you want with those temporary //variables, eg put them in some place in your html document //or store them in an associative array }) } }); 

我写了这个..非常简单的方法来获取一个健康的XML响应/字符串并用jquery解析它然后转换为数组。

 var response = 'something var xmlDoc = $.parseXML( response ); var myArray = getXMLToArray(xmlDoc); alert(myArray['root']['node1']); //Pop up window displaying the text "something" function getXMLToArray(xmlDoc){ var thisArray = new Array(); //Check XML doc if($(xmlDoc).children().length > 0){ //Foreach Node found $(xmlDoc).children().each(function(){ if($(xmlDoc).find(this.nodeName).children().length > 0){ //If it has children recursively get the inner array var NextNode = $(xmlDoc).find(this.nodeName); thisArray[this.nodeName] = getXMLToArray(NextNode); } else { //If not then store the next value to the current array thisArray[this.nodeName] = $(xmlDoc).find(this.nodeName).text(); } }); } return thisArray; } 

希望这可以帮助!!

如果您使用的是jQuery,那么parseXML会将整个xml doc 压缩为可用的数据结构。

我添加到你的脚本Troublesum

 function getXMLToArray(xmlDoc){ var thisArray = new Array(); //Check XML doc if($(xmlDoc).children().length > 0){ //Foreach Node found $(xmlDoc).children().each(function(){ if($(xmlDoc).find(this.nodeName).children().length > 0){ //If it has children recursively get the inner array var NextNode = $(xmlDoc).find(this.nodeName); thisArray[this.nodeName] = getXMLToArray(NextNode); } else { //If not then store the next value to the current array thisArray[this.nodeName] = []; $(xmlDoc).children(this.nodeName).each(function(){ thisArray[this.nodeName].push($(this).text()); }); } }); } return thisArray; } 

它现在还支持XML中具有相同名称的许多子节点。 FE

XML正在

    Germany Belgium 

countries.NL.borders [1]将给予德国。