Archive for June 1st, 2008

When 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.

  1.  
  2. var doc:XML=
  3. <DATA>
  4. <CATEGORY>
  5. <MEDIA>A.jpg</MEDIA>
  6. <MEDIA>B.jpg</MEDIA>
  7. </CATEGORY>
  8. <CATEGORY>
  9. <MEDIA>C.jpg</MEDIA>
  10. </CATEGORY>
  11. <CATEGORY>
  12. <MEDIA>D.jpg</MEDIA>
  13. </CATEGORY>
  14. <CATEGORY>
  15. <MEDIA>E.jpg</MEDIA>
  16. </CATEGORY>
  17. </DATA>;
  18.  
  19. var findName:String="media";
  20. trace(doc..*.(new RegExp(findName,"i")["test"](name())).toXMLString());
  21.  

:( "Error #1069: Property lowerCase not found on QName"

  1.  
  2. trace(doc..*.(name().lowerCase()=="media").toXMLString());
  3.  

:( Letter case must be same for this to work.

  1.  
  2. trace(doc..*.(name()=="MEDIA").toXMLString());
  3.  

Used a regular expression to do case-insensitive filter
:| Works, letter case does not matter...but the expression is too "hardcoded".

  1.  
  2. trace(doc..*.(/media/i.test(name())).toXMLString());
  3.  

:-? 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.

  1.  
  2. var findName:String="media";
  3. trace(doc..*.(new RegExp(findName,"i").test(name())).toXMLString());
  4.  

: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.

  1.  
  2. var findName:String="media";
  3. trace(doc..*.(new RegExp(findName,"i")["test"](name())).toXMLString());
  4.  

Comments 3 Comments »

Thanks for visiting www.keith-hair.net