Javascript XML数据到关联数组

Javascript XML Data to Associative Array

本文关键字:关联 数组 数据 XML Javascript      更新时间:2023-09-26

我有如下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[Blue Hawaiian[White朗姆酒=> 1,Blue Curaco => 2, Pineapple Juice => 1…],名称[镜头=>数量,…]]

现在我知道如何遍历XML,但是我不知道如何最好地将其转换为数组。

use 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中,如果是,则将其推入。

您要做的是创建一个对象图,这可以很容易地通过递归遍历XML树来实现。每个JavaScript对象都是一个映射(又名"关联数组",但我不喜欢这个术语,因为它们不是数组)。对象的属性可以通过带文字(obj.foo)的点符号来访问,通过带字符串(obj["foo"])的[]符号来访问:

var obj = {};            // A blank object
obj.foo = "bar";         // Now it has a property called "foo"
console.log(obj.foo);    // Accessing the property via dotted notation and a literal
console.log(obj["foo"]); // You can also use [] notation and a string
var s = "foo";
console.log(obj[s]);     // And of course the string can be the result of any expression,
                         // including coming from a variable

您可以看到[]表示法与字符串名称相结合,可以在遍历结构时轻松使用,以构建图形。您将访问与示例非常相似的结果,只是略有不同。我可能会选择以鸡尾酒名称作为键,然后有一个列出成分的ingredients属性(要么作为对象数组,要么仅使用成分名称作为键)。但是您可以选择不使用ingredients属性,而是让鸡尾酒对象直接包含配料,例如:

console.log(cocktails["Blue Hawaiian"]["White Rum"].name);       // "shot"
console.log(cocktails["Blue Hawaiian"]["White Rum"].quantity);   // 1

或者

var bh = cocktails["Blue Hawaiian"];
console.log(bh["White Rum"].name);       // "shot"
console.log(bh["White Rum"].quantity);   // 1

有很多不同的方法可以构建你的结果对象图,这取决于你想如何访问它和你的个人风格。

组成部分是:

  1. 创建对象。这很简单:

    var obj = {};
    
  2. 使用点点表示法向对象添加属性

    obj.propertyName = value;
    
  3. 使用括号表示法将属性添加到对象中,该属性的名称来自字符串表达式,而不是来自文字:

    obj["propertyName"] = value;
    // or
    var s = "propertyName";
    obj[s] = value;
    // or even
    var s1 = "property", s2 = "Name";
    obj[s1 + s2] = value;
    

    在您的示例中,您可能会从XML nodeNamenodeValue获得属性名称。

  4. 将一个对象放入另一个对象中。这实际上只是赋值给一个属性,你赋值的值是一个对象引用:

    var outer = {};
    var inner = {};
    inner.foo = "I'm foo";      // Putting the string "I'm foo" on propety `foo`
    outer.bar = inner;          // Putting the `inner` object on the property `bar`
    console.log(outer.bar.foo); // "I'm foo"
    

既然您已经知道如何遍历XML,那么您就可以根据遍历的结果构建对象图了。我不会写实际的代码来做这个因为,再一次,有很多决定要做关于你想要如何构建你的对象图的决定完全取决于你想要怎么做