Here’s a nice gotcha I found a while back when trying to run a filter on some XML data. If you write an attribute filter inside of a switch statement, the query will return null when you assign it to the XMLList variable. If you trace out the query instead of assigning it, it works fine.


switch (anything) {
case "testcase":
var xlData:XMLList = xmlData.Books.Book.(@author == 'Dickens');
break;
}

The above code will fail; apparently the scoping inside of switch statements is broken. There’s a bug report filed already, but it would be nice to see a fix for this.

6 Responses to “E4X Attribute Filter Doesn’t Work In Switch Statements”
  1. This has been driving me crazy for days!

    Found your site after the bug report gave me better search criteria.

    Have you found any solutions other than a giant IF statement?

  2. Nope, I haven’t found anything better, unfortunately. Glad this helped you troubleshoot though!

  3. Well, here’s the solution I came up with - maybe it will help others:

    //inside switch
    var xml:XMLList = getFilteredXML(myXML.node1.node2, “languag”, “english”);
    trace(xml);
    //end of switch

    private function getFilteredXML(_xml:XMLList, _attr:String, _val:String):XMLList {
    return _xml.(attribute(_attr) == _val);
    }

    Simply takes the E4X filter out of the switch by way of a function call - works well too!

  4. Yeah, this one nailed me today. I am surprised with as much e4x filtering as I use it didn’t nail me earlier.

    I didn’t have to use a function to fix, I simply declared the XML variable outside of the switch

    var x:XML;

    switch(item.name().toString()) {
    case “section”:
    x = content_data.section.(name == item.@label)[0];
    break;

    case “page”:
    x = content_data.section.page.(name == item.@label)[0];
    break;
    }

  5. Surround your switch case with { } i.e

    switch (anything) {
    case “testcase”:{
    var xlData:XMLList = xmlData.Books.Book.(@author == ‘Dickens’);
    }
    break;
    }

    should fix it.

    If you think about it, it kind of makes sense where the error is as inside a filter ‘this’ is scoped to the class however many methods are scoped to the current node thats being filtered. I can imagine the codes quite messy… :)

  6. Insane!!

    I’m so glad I found this and I’m not going mad. The braces solution works great. Of course you can also solve the problem by branching out of the switch statement into a new function too. Thanks! :-)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>