我已经看过很多关于如何在ArrayCollection中删除重复项的例子,但我似乎无法将其转换为XMLList。在大多数ArrayCollection示例中,该示例将数组的键与hasOwnProperty方法进行比较并返回bool。这没关系,但是在使用XMLList时我会比较什么呢?假设我有:
<fx:XML id="testXML" xmlns="">
<universe>
<category cname="cat 1">
<item iname = "All"/>
<item iname = "item 1"/>
<item iname = "item 2"/>
</category>
<category cname="cat 2">
<item iname = "All"/>
<item iname = "item 3"/>
<item iname = "item 4"/>
</category>
</universe>
</fx:XML>
[动作]
var myList:XMLList = testXML..@iname;
将出现两个项目“ALL”。 我知道我可能必须将XMLList转换为XMLListCollection以使用filterFunction(我将如何去做 - 或者我应该从一开始就将myList定义为XMLListCollection)。然后转到filterFunction:
private function remove Duplicate (item:Object): Boolean
{
here I don't know how to compare the item to tell me if the object already exist
or not. I guess I need to compare the item to a copy of the list and see if the
item has already been seen in the copy of the list. Or is there a clean way to
do this?
}
然后将所有这些传递给dropDownList:
<s:DropDownList id="myDDL" dataProvider="{myList}" />
答案 0 :(得分:3)
使用E4x filter function您可以将密钥放入Object
(如果密钥是字符串,否则使用字典而不是Object
)并查看它是否已经现在建立你的XMLList:
var xml:XML=<universe>
<category cname="cat 1">
<item iname="All"/>
<item iname="item 1"/>
<item iname="item 2"/>
</category>
<category cname="cat 2">
<item iname="All"/>
<item iname="item 3"/>
<item iname="item 4"/>
</category>
</universe>
function filter(xml:XML):XMLList {
var seen:Object={}
return xml..@iname.(!seen[valueOf()]&&(seen[valueOf()]=true))
}
trace( filter(xml) )
这是一个在wonderfl上的实例:http://wonderfl.net/c/10xr
答案 1 :(得分:1)
我知道如何执行此操作的最简单方法是使用ActionLinq。此代码将获取您的e4x代码并将其转换为Enumerable
,将属性转换为字符串,使列表中的项目不同并将其作为ArrayCollection
转储。
myList = Enumerable.from(testXML..@iname)
.cast(String)
.distinct()
.toArrayCollection();
如果您不想使用ActionLinq,可以使用Dictionary
实现此目的:
[Bindable]
private var myList:ArrayList;
private function removeDuplicates(data:XMLList):ArrayList {
var result:ArrayList = new ArrayList();
var found:Dictionary = new Dictionary();
for each(var item:String in data) {
if(item in found) {
continue;
}
found[item] = true;
result.addItem(item);
}
return result;
}
然后当XML准备就绪时,您可以调用它:
myList = removeDuplicates(testXML..@iname);