Javascript XML数据到关联数组 [英] Javascript XML Data to Associative Array
问题描述
我有如下所示的XML数据:
I have XML data which looks like this:
<?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 [Blue Hawaiian [White Rum => 1,Blue Curaco => 2,菠萝汁=> 1 ...],名称[shot =>数量,...]]
Using Javascript I would like to create a nested/associative array (or using objects) to look like: arrayName[Blue Hawaiian[White Rum => 1, Blue Curaco => 2, Pineapple Juice => 1...], name[shot => quantity, ...]]
现在我知道如何遍历XML,但是我不知道如何最好地将其转换为数组。
Now I know how to iterate through my XML, however I don't know how best to convert this into my array.
任何帮助
推荐答案
使用jquery.parseXML
use jquery.parseXML
var x = $.parseXML(xml_str);
var obj = {};
$(x).find("*").each(function(){
obj[this.nodeName] = $(this).text;
});
然后,您的obj是可以使用obj [ cocktail_list] [ cock_tail ] [ name]
我不在这里考虑数组。对于像cock_tail这样的数组,您将需要检查它是否已经在obj中,如果是,则将其推入。
Then you the obj is a json object you can manipulate with obj["cocktail_list"]["cock_tail"]["name"] I didn't consider the array here. For array like cock_tail, you will need to check whether it is already in the obj, and push it in if yes.
这篇关于Javascript XML数据到关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!