繁体   English   中英

Javascript XML数据到关联数组

[英]Javascript XML Data to Associative Array

我有看起来像这样的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>

使用Java语言,我想创建一个嵌套/关联数组(或使用对象),如下所示:arrayName [Blue Hawaiian [White Rum => 1,Blue Curaco => 2,Pineapple Juice => 1 ...],name [出手=>数量,...]]

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

任何帮助,将不胜感激。

使用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”]操作的json对象,我在这里没有考虑数组。 对于像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属性,而让cocktail对象直接包含这些成分,例如:

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,那么应该可以从遍历的结果构建对象图。 我没有编写实际的代码来执行此操作,这是因为,同样,要根据您希望如何构造对象图的方式做出许多决定,这些决定完全取决于您要如何执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM