Posted By

adrianparr on 07/20/11


Tagged

regex xml regexp remove as3 namespace


Versions (?)

AS3 Remove namespace from XML


 / Published in: ActionScript 3
 

URL: http://brianmriley.wordpress.com/2008/03/14/remove-xml-namespaces-in-flex-or-as3/

If you don't deal with namespaces in XML correctly they can break your parsing in AS3. One way of getting around this is to remove the namespace from the XML a using regular expression.

  1. package {
  2.  
  3. import flash.display.MovieClip;
  4. import flash.net.URLLoader;
  5. import flash.net.URLRequest;
  6. import flash.net.URLLoaderDataFormat;
  7. import flash.events.Event;
  8. import flash.events.IOErrorEvent;
  9.  
  10. public class Main extends MovieClip {
  11.  
  12. public function Main() {
  13. var xmlLoader:URLLoader = new URLLoader();
  14. xmlLoader.dataFormat = URLLoaderDataFormat.TEXT;
  15. xmlLoader.addEventListener(Event.COMPLETE, onXmlLoader_COMPLETE);
  16. xmlLoader.addEventListener(IOErrorEvent.IO_ERROR , onXmlLoader_IO_ERROR);
  17. xmlLoader.load(new URLRequest("data.xml"));
  18. }
  19.  
  20. private function onXmlLoader_COMPLETE(e:Event):void
  21. {
  22. var myXml:XML = new XML(e.target.data);
  23. var myXmlStr:String = myXml.toString();
  24. var xmlnsPattern:RegExp = new RegExp("xmlns[^\"]*\"[^\"]*\"", "gi");
  25. myXmlStr = myXmlStr.replace(xmlnsPattern, "");
  26. myXml = new XML(myXmlStr);
  27. trace(myXml.message);
  28. }
  29.  
  30. private function onXmlLoader_IO_ERROR(event:IOErrorEvent):void
  31. {
  32. trace("onXmlLoader_IO_ERROR()");
  33. trace("event.text: "+String(event.text));
  34. }
  35.  
  36. }
  37. }
  38.  
  39. ///////////////////////////////////////////////////////////////////
  40. // The 'data.xml' looks like this ...
  41. //
  42. // <?xml version="1.0" encoding="utf-8" ?>
  43. // <root xmlns="http://www.adrianparr.com">
  44. // <message>Hello World</message>
  45. // </root>
  46. //
  47. //
  48. // And the output will be ...
  49. //
  50. // Hello World

Report this snippet  

You need to login to post a comment.