Case-insensitive E4X filtering
Posted by: Keith H in XML, tags: E4X Filtering, Regular Expressions, XMLWhen I'm writing a script to read XML data, I personally like the identification of node names and attributes to be case-insensitive. Its one less thing to worry about when others are modifying the XML data that my script will have to read and render, and I think they feel modifying the XML to be more user-friendly this way.
Here, the example scripts pull a list of all the nodes with the name "MEDIA".
Using Regular Expressions, you can identify each "MEDIA" node regardless of its letter case.
var doc:XML= <DATA> <CATEGORY> <MEDIA>A.jpg</MEDIA> <MEDIA>B.jpg</MEDIA> </CATEGORY> <CATEGORY> <MEDIA>C.jpg</MEDIA> </CATEGORY> <CATEGORY> <MEDIA>D.jpg</MEDIA> </CATEGORY> <CATEGORY> <MEDIA>E.jpg</MEDIA> </CATEGORY> </DATA>; var findName:String="media"; trace(doc..*.(new RegExp(findName,"i")["test"](name())).toXMLString());
"Error #1069: Property lowerCase not found on QName"
trace(doc..*.(name().lowerCase()=="media").toXMLString());
Letter case must be same for this to work.
trace(doc..*.(name()=="MEDIA").toXMLString());
Used a regular expression to do case-insensitive filter
Works, letter case does not matter...but the expression is too "hardcoded".
trace(doc..*.(/media/i.test(name())).toXMLString());
Works, but compiler does not like it:
"Warning: 3594: test is not a recognized method of the dynamic class RegExp."
This is an attempt to allow variables and expressions.
var findName:String="media"; trace(doc..*.(new RegExp(findName,"i").test(name())).toXMLString());
:jumping: Works!
"[" and "]" keeps the compiler from warning when using the RegExp "test()" method.
Now letter case does not matter, and RegExp constructor allows variables or expressions.
var findName:String="media"; trace(doc..*.(new RegExp(findName,"i")["test"](name())).toXMLString());
Entries (RSS)