XML Namespaces in AS3: XMLNamespaceProxy
Quick note about a neato class I just added to guttershark. I’ve been working with SOAP in AS3 lately. Man is it a pain in the butt. So I’m doing my best to make sure I don’t have to write this crap again.
One other quick note before I show you the namespace proxy. I’ve integrated a SoapService in with the ServiceManager. It’s fairly easy to setup now. You can read all about that in the docs.
On to the XMLNamespaceProxy. With soap, when you get a result back - there are a couple steps you need to go through. Usually looks something like this:
var result:XML=new XML(mySoapResultXML); var ns:Namespace=result.namespace(); var body:XML=result.ns::Body;
This sets you up with whatever is in the body of the soap result. Which is pretty simple. But now I have to snoop through the content of the body - which in my case (the service I’m using) has custom namespaces in the result. Here’s my initial code looked like:
var targetNodes:XML=body.ns::rawValues.ns::bud09Out; trace(targetNodes.ns::totalIncome); //give me a value im looking for
The service I’m hitting has namespaces in the responses, so in order to find the actual values needed I have to prefix everything with the qualifying namespace. Arg!
Here’s entire code snippet with xml namespace proxy integrated:
var result:XML=new XML(mySoapResultXML); var ns:Namespace=result.namespace(); var body:XML=result.ns::Body; var targetNodes:XML=body.ns::rawValues.ns::bud09Out; //the good stuff: var xnp:XMLNamespaceProxy=new XMLNamespaceProxy(targetNodes,ns); //now I can use the xml namespace proxy just like normal: trace(xnp.totalIncome); //or... trace(xnp.years.year[0].@category);
After you create an XMLNamespaceProxy object, every call get’s prefixed with the qualifying namespace and forwarded to the actual XML object. No more namespace prefix’s. Yay!
As you’re reading through the XML. The proxy will return instances of XMLNamespaceProxy’s (if the target is XML), or it will return a normal XMLList which you can iterate over.
And as usual, check the docs.
Enjoy!
4 Comments so far
Leave a reply
Have you tried…
–
var result : XML = new XML( mySoapResultXML );
default xml namespace = result.namespace();
var body : XML = result.Body;
var targetNodes : XML = body.rawValues.bud09Out;
AH. Is that the “correct” solution. I was looking all over for something like that. I couldn’t find anything to point me to that conclusion. Thanks for that. I’ll give that a shot.
I’m going to keep my class in guttershark anyway. That default namespace directive seems to only work in the scope of where your accessing the xml. So for example, if I passed off the xml to another class, i’d have to setup the default xml namespace again before accessing nodes. Which isn’t that big of deal, but I’d rather not worry about it.
No worries, just thought it was worth pointing out - it’s a sanity saver for me, anyway. :-)