如何从XML中的所有后代中删除特定属性?

时间:2012-02-27 06:34:01

标签: xml actionscript-3 flex xml-attribute

我有像

这样的XML
var test:XML = new XML( <record id="5" name="AccountTransactions"
    <field id="34" type="Nuber"/>
    </record>);

我想删除除id之外的所有属性,并在XML的所有节点中键入。通过这段代码,我无法做到这一点。除了循环,你能建议更好的解决方案。

var atts:XMLListCollection = new XMLListCollection(test.descendants().attributes().((localName() != "id") && (localName() != "type")));
atts.removeAll(); trace(test)

它仍然显示所有属性:/

2 个答案:

答案 0 :(得分:1)

var xml:XML = new XML(
    <record id="5" name="AccountTransactions">
        <field id="34" type="Number">
            <test id="0"/>
        </field>
    </record>);

//make array of attribute keys, excluding "id" and "type"
var attributesArray:Array = new Array();
for each (var attribute:Object in xml.attributes())
{
    var attributeName:String = attribute.name();
    if (attributeName != "id" && attributeName != "type")
    {
        attributesArray.push(attributeName);
    }
}

//loop through filtered attributes and remove them from the xml
for each (var attributeKey:String in attributesArray)
{
    delete xml.@[attributeKey];
    delete xml.descendants().@[attributeKey];
}

答案 1 :(得分:1)

    var test:XML = new XML( '<record id="5" name="AccountTransactions"><field id="34" type="Nuber" score="ded"/><field id="35" type="Nuber" score="sc"/></record>');
    var attributes:XMLList = test.field.@*;
    var length:int = attributes.length();
    for (var i:int = 0; i < length; i++) {
        (attributes[i].localName() != "id" && attributes[i].localName() != "type") ? [delete attributes[i], length--] : void;
    }
    trace(test);