E4X Filtering

Actionscript:
  1. var userInfo:XML = <users>
  2.   <user fname="joe" lname="smith" age="31" />
  3.   <user fname="mildred" lname="calder" age="64" />
  4.   <user fname="ben" lname="nathanson" age="20" />
  5.   <user fname="james" lname="biuford" age="19" />
  6.   <user fname="nick" lname="calhoun" age="45" />
  7. </users>;
  8.  
  9.  
  10. trace("Users over 20:\n");
  11. trace(userInfo.user.(@age> 20).toXMLString());
  12.  
  13. trace("\nUsers with the name nick:\n");
  14. trace(userInfo.user.(@fname == "nick" ).toXMLString());
  15.  
  16. // use regular expressions with e4x
  17. trace("\nUsers with name starting with j:\n");
  18. trace(userInfo.user.(/^j/.test(@fname)));
  19.  
  20. /*
  21. outputs:
  22.  
  23. Users over 20:
  24.  
  25. <user fname="joe" lname="smith" age="31"/>
  26. <user fname="mildred" lname="calder" age="64"/>
  27. <user fname="nick" lname="calhoun" age="45"/>
  28.  
  29. Users with the name nick:
  30.  
  31. <user fname="nick" lname="calhoun" age="45"/>
  32.  
  33. Users with name starting with j:
  34.  
  35. <user fname="joe" lname="smith" age="31"/>
  36. <user fname="james" lname="biuford" age="19"/>
  37.  
  38. */

One of the nicest features of E4X is filtering. The above code shows a few simple examples ... the last example makes use of regular expressions -- I first read using regular expressions and E4X somewhere on http://www.darronschall.com/.

I usually prefer to use a database for any kind of info I'll be searching... but if you know you have a relatively small amount of data XML can be a fine way to go.

This entry was posted in XML and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Jon
    Posted January 21, 2010 at 10:06 am | Permalink

    if you have a comma delineated string in XML, how can you search each item in the arrray using this method?

    i.e.

    look for items with ted

  2. Jon
    Posted January 21, 2010 at 10:08 am | Permalink

    comment box doesnt like code…

    i.e. [xml] item value=”bob, george, ted” [/xml]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*