Search code examples
xmlactionscript-3dynamice4x

Dynamic E4X expressions


My last Q: E4X select Nodes where descendants can be either A OR B or A && B was concerning how to query for multiple attribute values in E4X expressions, which @Patrick answered with this:

xml.Item.(descendants('ProductRange').(@id=="1" || @id=="2").length()>0);

Now the question is, how do we make the values dynamic using an array or string?

A bit like this, but this DOES NOT work:

var attributeValues:String = "@id==\"1\" || @id==\"2\" || @id==\"3\" || @id==\"4\"";
xml.Item.(descendants('ProductRange').(attributeValues).length()>0);

Many Thanks


Solution

  • An array holding your values can be made for example and then using an indexOf search to find the id in it :

    var xml:XML=<Items>
    <Item name="aaa">
        <ProductRanges>
            <ProductRange id="1" />
        </ProductRanges>
    </Item>
    <Item name="bbb">
        <ProductRanges>
            <ProductRange id="2" />
        </ProductRanges>
    </Item>
    <Item name="ccc">
        <ProductRanges>
            <ProductRange id="1" />
            <ProductRange id="3" />
            <ProductRange id="2" />
        </ProductRanges>
    </Item>
    </Items>;
    
    // you values filled from whatever source
    var valuesToFind:Array=["1","2", "3"]; 
    
    // search if @id exist into your values
    // and unsure that there is any node returned
    var res:XMLList=xml.Item.(descendants('ProductRange').(valuesToFind.indexOf(@id.toString())>=0).length()>0);
    trace(res);