14
Mar
08

Remove Annoying XML Namespaces in Flex/AS3

My buddy pointed out another approach that I show here — it’s easier and doesn’t actually remove the namespace.
XML namespaces can be a real pain in the a$$ in AS3, so I often just rip them out. I mean think about it…when you get some XML payload back in a web service response, do you really care or need the namespace? Nah….just rip that bad boy out and starting using your XML baby.
Here’s my quick and dirty AS3 XML Namespace Ripper — for the sake of argument and a quick example, just assume this is in a Responder object like a Caringorm business delegate, but it should probably exist in a static XML util:
public function result(response:Object):void
{
var xmlString:String;
var xmlnsPattern:RegExp;
var namespaceRemovedXML:String;
var responseXML:XML;

// get the XML payload
if(ResultEvent(response).result is XMLList)
{
response = ResultEvent(response).result as XMLList;
}
else
{
response = ResultEvent(response).result as XML;
}

// convert it to a string
xmlString = response.toXMLString();

// define the regex pattern to remove the namespaces from the string
xmlnsPattern = new RegExp("xmlns[^\"]*\"[^\"]*\"", "gi");

// remove the namespaces from the string representation of the XML
namespaceRemovedXML = xmlString.replace(xmlnsPattern, "");

// set the string rep. of the XML back to real XML
responseXML = new XML(namespaceRemovedXML);

// do something with the XML
}
Thanks for the quick refresher on regex Johnny!
Advertisements

29 Responses to “Remove Annoying XML Namespaces in Flex/AS3”


  1. March 14, 2009 at 3:45 pm

    It blows up if there is more than one namespace however, because the children elements that use typed namespaces are then not bound. I changed regex to

    new RegExp(“xmlns=[^\”]*\”[^\”]*\””, “gi”);

    to just remove the default namespace and it worked great. I can still access the bound children using the :: syntax. Anyways, thanks for the example.

  2. 2 Eric Belair
    March 23, 2009 at 4:52 pm

    This is a great post. I’ve been working on this all day, and this is the only solution I’ve found that works! Thanks!!!

  3. 3 Joe
    April 3, 2009 at 3:26 pm

    Just curious about the reasoning…

    Why don’t you just use the namespace that is sent back? If you are calling the web service you’ll know what namespace is being returned.

    namespace nsToUse = “http://api.website.com/api/”;
    use namespace nsToUse;

    var xlc:XMLListCollection = new XMLListCollection(xml.YourNodeHere);

    Much better for performance.

    • 4 Matt Rooney
      May 18, 2009 at 9:32 am

      @Joe:

      Because if you try to use the XMLListCollection as a dataprovider for a DataGrid it will not work without using a labelFunction.

  4. May 18, 2009 at 4:38 pm

    This is a great post. I’ve been working on this all day, and this is the only solution I’ve found that works! Thanks!!!

  5. July 7, 2009 at 3:40 am

    what you should do is use a namespace proxy object – everything you attempt to access first goes through the proxy object, forwards the call the XML object, but automatically prefixes it with the namespace.

    like this:

    http://codeendeavor.com/gsdocs/net/guttershark/util/XMLNamespaceProxy.html

  6. 7 Tom
    October 26, 2009 at 7:21 am

    You should not remove the namespace!

    A very easy way to get rid of them, is:

    Replace the :: by _ !

    <media::thumbnail .. becomes <media_thumbnail …

    No namespace, but no conflict in your XML!

    That is the solution!

  7. January 20, 2010 at 3:50 am

    Here is a regexp to remove the prefixes

    private static const prefixPattern:RegExp = /(<[\/]*)([\w]*:)/gi;
    namespaceRemovedXML.replace(prefixPattern, "$1");

  8. February 3, 2010 at 1:51 pm

    This was my ultimate solution:

    xmlString = xmlString.replace( new RegExp(“xmlns(:[A-Za-z0-9]+)?=[^\”]*\”[^\”]*\””, “gi”), “” );
    xmlString = xmlString.replace( new RegExp( “<*:", "gi" ), "_" );

    its a combination of the above because :

    – xmlns attributes also can have a namespace
    – if not removed. this will conflict with the second underscore-search-replace trick
    – now it works correctly on youtube rss

  9. 12 Diogo simões
    July 7, 2010 at 1:23 pm

    Man, you just made my day! That’s just what I needed. Cheers!!

  10. March 29, 2011 at 11:50 pm

    One of the best blog i have seen recently..

  11. April 19, 2011 at 11:04 am

    I’ve been playing around with the issue of removing or replacing the default xml namespace without string operations. Here is my solution:

    private function replaceDefaultNameSpace (src:XML, ns:Namespace):void
    {
    var tempNs:Namespace = new Namespace (“temp”);
    var node:XML;

    src.addNamespace(tempNs);
    src.setNamespace(tempNs);

    for each (node in src.descendants()) node.setNamespace(tempNs);

    src.addNamespace(ns);
    src.setNamespace(ns);

    for each (node in src.descendants()) node.setNamespace(ns);

    src.removeNamespace(tempNs);

    trace (src.toXMLString());
    }

    //call the function like this
    replaceDefaultNameSpace(src, new Namespace());
    //or this
    replaceDefaultNameSpace(src, new Namespace(“”, “http://uri.com”));

  12. June 17, 2011 at 8:30 am

    thx for this! you really made my day 🙂

    i was just wondering, why the hell the “removeNamespace” method doesn’t work as i expected to do…

  13. October 26, 2011 at 11:08 am

    bayan escort siteleri istanbul er r

  14. 17 paul
    April 5, 2012 at 7:23 pm

    laughed my a$$ off man hhaahahaahahahaahahaahaha

  15. November 23, 2012 at 10:26 am

    At this time it appears like BlogEngine is the best
    blogging platform out there right now. (from what I’ve read) Is that what you’re using on your
    blog?

  16. June 21, 2013 at 6:38 pm

    Howdy very cool site!! Guy .. Beautiful .. Amazing .. I’ll bookmark your blog and take the feeds also? I’m happy
    to seek out numerous helpful information here in
    the publish, we need develop extra strategies in this regard, thank you for sharing.
    . . . . .

  17. June 23, 2013 at 5:25 pm

    These blisters will take about five days. According
    to the Centers for Disease Control and Prevention
    recommends that all children receive shin splints running vaccine.
    On reaching the colony medical team distributed medicines
    to people and asked the colony residents to maintain hygiene to
    prevent Shin Splints Running, therefore infecting them as well.

    The disease is highly contagious.

  18. July 24, 2013 at 10:24 am

    Hello my friend! I wish to say that this article is amazing, great
    written and include approximately all vital infos.

    I would like to look more posts like this .

  19. November 28, 2013 at 12:25 am

    [url=http://www.canadabootsoutlets.com/ugg-bailey-bow-boots-3280-black-p-142.html]UGG Bailey Bow Boots 3280 Black[/url] William St.For dry, sparse and thinning hair, combine 4 drops of patchouli oil and 5 drops of ylang ylang oil with 250ml of distilled water and 5ml of cider vinegar.The event is sponsored by Xi Theta Zeta Chapter of Beta Sigma Phi.” DesLauriers said the investigation “is in its infancy,” but more than 1,000 lawenforcement officers from several agencies are chasing the more than 2,000 leads that have been received. [url=http://www.cheapestbootssaleinuk.co.uk/ugg-roxy-short-boots-5828-black-p-190.html]UGG Roxy Short Boots 5828 Black[/url]]
    [url=http://www.canadabootsoutlets.com/ugg-coquette-slipper-5125-sand-p-12.html]UGG Coquette Slipper 5125 Sand[/url] “I train with all the Level 6 girls that were here and know pretty much everyone in the higher levels, so you want to do well in front of them, too.Noon Sept.(5 cm).All the same, it has a lot of additional benefits that are not so substantially recognized. [url=http://www.cheapestbootssaleinuk.co.uk/ugg-erin-boots-5202-sand-p-38.html]UGG Erin Boots 5202 Sand[/url]
    [url=http://www.canadabootsoutlets.com/ugg-bailey-button-boots-5803-tomato-red-p-124.html]UGG Bailey Button Boots 5803 Tomato Red[/url] Rather than put pen to paper and write romantic words to a loved one it seems that we now prefer to use digital media to send our messages of love.Senator Mark Warner has not.Their ranks had been steady, between 30 and 33 percent, but rose last year to 47 percent, according to the latest survey.It can reduce the discomfort you have while at work esp when used with regular stretching and strengthening exercises. [url=http://www.cheapestbootssaleinuk.co.uk/ugg-metallic-classic-short-boots-5842-black-p-263.html]UGG Metallic Classic Short Boots 5842 Black[/url]

    The west has derived a physiologic philosophy of wellness while the energetic theories are more eastern. [url=http://caboots.pediatrictables.com]uggs canada[/url] ” 4) Moments of retaining energy “I gained strength Through my weakness, strength emerged.Matt’s a good son, a good husband, a good father and a good worker.
    [url=http://frbottes.morekissesplease.com]ugg pas cher[/url] For that much less informed, a Happy ending massage is really a therapeutic massage that’s performed by a woman on the guy, and also the girl surface finishes from the guy with a real handjob or even more.(125 ml) Motts Clamato cocktail Fresh grapes, garnishPour all ingredients into a wine glass and fill twothirds with ice. [url=http://jacketwear.tumblr.com]barbour jacka dam[/url]

  20. April 11, 2015 at 7:39 pm

    this is working for this xml :


    true

    ….

    function resultFunc(evt:ResultEvent):void
    {
    var veri:XML = new XML(evt.message.body);
    var sonuc:XML = xmlTemizle(replaceDefaultNameSpace(veri, new Namespace(“”,”http://tempuri.org/”)));
    trace (sonuc.Body.LoginResponse.LoginResult);
    }

    function replaceDefaultNameSpace (src:XML, ns:Namespace):String
    {
    var tempNs:Namespace = new Namespace (“temp”);
    var node:XML;
    src.addNamespace(tempNs);
    src.setNamespace(tempNs);

    for each (node in src.descendants()) node.setNamespace(tempNs);
    src.addNamespace(ns);
    src.setNamespace(ns);

    for each (node in src.descendants()) node.setNamespace(ns);
    src.removeNamespace(tempNs);
    return src.toString();
    }

    function xmlTemizle(gelen:String):XML
    {
    gelen = gelen.replace( new RegExp(“xmlns(:[A-Za-z0-9]+)?=[^\”]*\”[^\”]*\””, “gi”), “” );
    gelen = gelen.replace( new RegExp( “<*:", "gi" ), "_" );

    return new XML(gelen.replace(/[\u000d\u000a\u0008]+/g,""));

    }

    • 25 Houtan Maleki
      October 27, 2016 at 1:50 am

      All these seem to rely on two regex replace calls
      1) search “xmlns(:[A-Za-z0-9]+)?=[^\”]*\”[^\”]*\”” and replace with “”
      2) “<*:" and replace with "_"

      The first regex should have be \sxmlns to catch the white space before xmlns
      The second regex seems to replace all semicolons inside tag. Such as the : in time strings. I found a simpler approach. As I generally know which name spaces I will encounter in a project so I use the following alternative for (2) for example if I know I will see <soap: <xsi: <xsd: <a: <c: <hc: I use a look behind regex search for
      2alt) "(?<=(soap|xsi|xsd|a|c|hc)):" and replace with "_"
      ie. match colon follows (ie look behind (?<): that contains soap etc.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: