xmlactionscript-3e4x

How do I filter by attribute and value across multiple elements?


I'm trying to find a XML node by checking it's type (type is an attribute). I can do this successfully with the following code:

var xml:XML = describeType(this);
var classname:String = getQualifiedClassName(mainGroup);
var xmlList:XMLList = xml.accessor.(@type==classname);
if (xmlList.length()) {
    trace("Found:" + xmlList[0]);
}

But I do not know if it will always be an "accessor" element. It could be an "variable" element or possibly something else. So I want to search all elements in the XML that have a type attribute that has a value that matches the value I'm looking for. When I use the following it says it's invalid:

// 1084: Syntax error: expecting doublecolon before semicolon.
var xmlList:XMLList = xml..(@type==classname);

What is the correct syntax to get the information I'm looking for?

Here is some XML to test with:

<type name="MyApplication" base="spark.components::WindowedApplication" isDynamic="false" isFinal="false" isStatic="false">
    <accessor name="explicitMinWidth" access="readwrite" type="Number" declaredBy="mx.core::UIComponent"/>

    <accessor name="mainGroup" access="readwrite" type="components::MainGroup" declaredBy="MyApplication">

    </accessor>

    <variable name="controlBarGroup" type="spark.components::Group">

    </variable>
</type>

Solution

  • What about using the * like this :

    var xml:XML = <type name="MyApplication" base="spark.components::WindowedApplication" isDynamic="false" isFinal="false" isStatic="false">
        <accessor name="explicitMinWidth" access="readwrite" type="Number" declaredBy="mx.core::UIComponent" />
        <accessor name="mainGroup" access="readwrite" type="components::MainGroup" declaredBy="MyApplication" />
        <variable name="controlBarGroup" type="spark.components::Group" />
        <variable name="explicitMinWidth" access="readwrite" type="Number" declaredBy="mx.core::UIComponent" />
    </type>;
    
    var xml_list:XMLList = xml.*.(@type == 'Number');
    trace(xml_list.length());   // gives : 2
    

    EDIT :

    To avoid the error Error #1065: Variable type is not defined and drop lines which didn't contain the type attribut, you can use :

    var xml_list:XMLList = xml.*.(attribute('type') == 'Number');
    trace(xml_list.length());   // gives : 2
    

    Hope that can help.