May
30
2008
Find and Replace for XML in AS3
Posted by: Keith H in ActionScript 3, XML, tags: ActionScript 3, XMLThese are some functions I wrote for finding and replacing parts of XML using AS3.
Not sure if E4X or "XML.replace()" method can be used to make each function's task better.
/*----------------------------------- Recursively replace nodeNames. -------------------------------------*/ private function findAndReplaceTagNames (xml:XML,find:String,replace:String):XML { if(xml.localName() == find){ xml.setLocalName(replace); } var n:int=0; var c:XML; while(n <xml.children().length()){ c=xml.children()[n]; findAndReplaceTagNames(c,find,replace); n++; } return xml; } /*----------------------------------------- Recursively replace attributes. -------------------------------------------*/ private function findAndReplaceAttributeNames (xml:XML,find:String,replace:String,in_tags_named:String=""):XML { var ok:Boolean=true; if(in_tags_named != "" && xml.localName() != in_tags_named){ ok=false; } if(xml.@[find] != null && ok){ xml.@[replace]=xml.@[find]; delete xml.@[find]; } var n:int=0; var c:XML; while(n <xml.children().length()){ c=xml.children()[n]; findAndReplaceAttributeNames(c,find,replace); n++; } return xml; } /*--------------------------------------------- Recursively find and remove attributes. -----------------------------------------------*/ private function findAndRemoveAttributeNames (xml:XML,find:String,in_tags_named:String=""):XML { var ok:Boolean=true; if(in_tags_named != "" && xml.localName() != in_tags_named){ ok=false; } if(xml.@[find] != null && ok){ delete xml.@[find]; } var n:int=0; var c:XML; while(n <xml.children().length()){ c=xml.children()[n]; findAndRemoveAttributeNames(c,find); n++; } return xml; }
Entries (RSS)
Thank you for posting findAndRemoveAttributeNames function! Really helped me!
That’s a nice example of XML eating syntax.
Another little trick…
xml = new XML(xml.toXMLString().replace(regex,replacement));
Notionally it’s just like opening the XML file in an editor and doing a regular expression search and replace.
When it works, it works great, but there are many situations where it won’t work, and it can become a trap for the unwary.
One particular example is just ‘hacking’ a remote web site with links to ‘http://somewhere.live/etc’ to ‘./localfolder’ when you load XML, so that you can test lots of XML configured website crapola without maintaining a second copy of EVERYTHING.