AS2 XML 解析、循环、数组和对象
我想用 AS2 解析 XML 文件,但我不确定如何将检索到的值放入一个对象数组中,其中键的数量与找到的值匹配。代码中有 if 语句来过滤掉不需要的元素,但数组键的数量将始终等于 for 循环的长度限制。
如何创建仅包含未定义值的对象数组?
//AS2
var xml:XML = new XML();
xml.ignoreWhite=true;
xml.onLoad = function(success)
{
if (success)
{
var myImage = xml.firstChild.childNodes;
var img_arr = new Array();
for (i=0; i<myImage.length; i++)
{
img_arr[i] = new Object();
var nodeName = xml.firstChild.childNodes[i].NodeName;
//condition to filter out values
if (nodeName == "value")
{
img_arr[i]["file"] = xml.firstChild.childNodes[i].firstChild.NodeValue;
img_arr[i]["name"] = xml.firstChild.childNodes[i].childNodes[1].NodeValue;
}
}
//trace(img_arr.length)
}
}
xml.load("test.xml");
返回一个数组,例如:
img_arr[文件][0] = 值0
img_arr[名称][0] = 名称0
img_arr[文件][1] = 未定义
img_arr[名称][1] = 未定义
img_arr[文件][2] = 值2
img_arr[名称][2] = 名称2如何获得这个数组?
img_arr[文件][0] = 值0
img_arr[名称][0] = 名称0
img_arr[文件][1] = 值2
img_arr[名称][1] = 名称2
I want to parse an XML file with AS2, but I'm not sure how to put the retrieved values into an array of objects with the number of keys matching found values. The code has if statements to filter out unwanted elements, but the number of array keys will always equal the length limit of the for loop.
How do I create an array of objects that only contains values that are not undefined?
//AS2
var xml:XML = new XML();
xml.ignoreWhite=true;
xml.onLoad = function(success)
{
if (success)
{
var myImage = xml.firstChild.childNodes;
var img_arr = new Array();
for (i=0; i<myImage.length; i++)
{
img_arr[i] = new Object();
var nodeName = xml.firstChild.childNodes[i].NodeName;
//condition to filter out values
if (nodeName == "value")
{
img_arr[i]["file"] = xml.firstChild.childNodes[i].firstChild.NodeValue;
img_arr[i]["name"] = xml.firstChild.childNodes[i].childNodes[1].NodeValue;
}
}
//trace(img_arr.length)
}
}
xml.load("test.xml");
Returns an Array like:
img_arr[file][0] = value0
img_arr[name][0] = name0
img_arr[file][1] = undefined
img_arr[name][1] = undefined
img_arr[file][2] = value2
img_arr[name][2] = name2How do you get this array?
img_arr[file][0] = value0
img_arr[name][0] = name0
img_arr[file][1] = value2
img_arr[name][1] = name2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试在将空值推入数组之前查找它们。
类似于:
使用值的长度来查找其是否为空,将它们视为字符串,有时会很有用:如果为 0,则意味着在 nodeValue 中未找到任何字符,表明该节点没有找到任何字符不存在,或者节点为空。
使用您的代码,这就是我的建议(必须适合您正在做的事情,尚未经过测试):
You could try to look for empty values before pushing them into your array.
Something like :
Using the length of the value to find if its null or not, looking at them as String, can be useful sometimes : if its 0, that means that no character have been found in the nodeValue, showing that either the node doesn't exists, or the node is empty.
Using your code, here's what I suggest (must propably adapted to what you're doing, have not been tested) :