我有如下所示的 XML 数据:
<?xml version='1.0' encoding='ISO-8859-1'?>
<cocktail_list>
<cocktail>
<name> Blue Hawaiian </name>
<ingredient>
<quantity>1</quantity>
<shot>White Rum</shot>
</ingredient>
<ingredient>
<quantity>1</quantity>
<shot>Blue Curacao</shot>
</ingredient>
<ingredient>
<quantity>2</quantity>
<shot>Pineapple Juice</shot>
</ingredient>
<ingredient>
<quantity>1</quantity>
<shot>Coconut Cream</shot>
</ingredient>
</cocktail>
<cocktail>...
</cocktail_list>
使用 Javascript 我想创建一个嵌套/关联数组(或使用对象),如下所示: arrayName[蓝色夏威夷[白朗姆酒 => 1,蓝色库拉科 => 2,菠萝汁 => 1...],名称[镜头 => 数量,...]]
现在我知道如何迭代 XML,但我不知道如何最好地将其转换为数组。
如有任何帮助,我们将不胜感激。
最佳答案
使用jquery.parseXML
var x = $.parseXML(xml_str);
var obj = {};
$(x).find("*").each(function(){
obj[this.nodeName] = $(this).text;
});
那么你的 obj 是一个 json 对象,你可以用 obj["cocktail_list"]["cock_tail"]["name"] 操作 我这里没有考虑数组。对于像cock_tail这样的数组,你需要检查它是否已经在obj中,如果是则将其插入。
关于Javascript XML 数据到关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8111395/