Accessing XML with namespaces in AS3 Flex AIR
Accessing xml elements in AS3 with namespaces isn’t straight forward. I recently had an occasion where I had some incoming xml that defined a namespace in the root element. When I initially tried to traverse the xml structure to get an xmlList of elements I wasn’t getting anything. I was puzzled at first but then I saw the xml had defined a namespace and I thought that might be the culprit. Figuring out how to read the xml with standard E4X syntax root.element.childelement etc. took some time since I never had to work with this before. Maybe somebody else searching for a solution to this will come accross this and save themselves some time.
Basically I had some xml coming in from a request that looked like this:
<xml>
<serviceResponse xmlns=”http://cafesilencio.net/doc/blahblahblah/”>
<someElement>
<childElement>twinkies are yummy</childElement>
<childElement>donuts are delicious</childElement>
</someElement>
<serviceResponse>
</xml>
The following code WON’T work:
var childList:XMLList = serviceResponse.someElement.childElement;
The xml is sort of locked or maybe protected would be a better word. So to access it you can first declare a namespace. Then you call a directive to use the namespace before traversing the xml. So one way to do it would look like this:
package com.mypackage.util
{
public class MyClass
{
//declare the namespace,
//notice it's the same as the xmlns attribute in the root of the xml
private namespace cafesilencioNameSpace = "http://cafesilencio.net/doc/blahblahblah/";
...
public function doSomethingWithTheXML(xmlDoc:XML):void
{
//this is important, we're indicating we want to use a specific namespace
use namespace cafesilencioNameSpace;
var childList:XMLList = xmlDoc.someElement.childElement;
//do something with the childList
}
}
This isn’t the only way to do it but it worked for me and now I can get back to coding.
About this entry
You’re currently reading “Accessing XML with namespaces in AS3 Flex AIR,” an entry on Cafe Silencio
- Published:
- 10.09.08 / 7pm
- Category:
- code snippets, stuff i learned
olso can aid in your development of SimpleDB applications with its intuitive graphic user interface (gui).- Cafe Silencio has created a powerful tool to explore SimpleDB. Instead you can spend your time developing your SimpleDB solution.
Easily and securely share files between you and your clients, colleagues, and friends with Kaze Cloud.- Another powerful tool from Cafe Silencio
No comments
Jump to comment form | comments rss [?] | trackback uri [?]