AS3 and xml namespaces

Over the past few days I've been encountering problems reading XML nodes where there is a default namespace defined in the xml.

   

For example:

var example1:XML = <RootNode>
  <Child>This is the child</Child>
</RootNode> ;
trace(example1.Child); // traces 'This is the child'

var example2:XML = <RootNode xmlns="http://tempuri.org/">
  <Child>This is the child</Child>
</RootNode> ;
 trace(example2.Child); // traces nothing

The simple solution would be to not  include the namespace definition in the xml, but when the xml is server generated that isn't really an option.
Roger Braunstein writes that the problem is that example2.Child returns null because it is searching for a non-namespaced node where all the nodes exist in the xmlns namespace (I'll take his word on that) and that a solution is to define the namespace in an .as file and then set your xml reading code to use the namespace eg:

//xmlns.as
package
{
    public namespace xmlns = "http://tempuri.org/";
}

 

//in your xml reading class
use namespace xmlns; 

var example3:XML = <RootNode xmlns="http://tempuri.org/">
  <Child>This is the child</Child>
</RootNode> ;
trace(example3.Child); // traces 'This is the child'

 

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Похожие записи

Comments

March 10. 2009 20:44

THANK YOU!
i want to be a farmer!

plantgod

May 21. 2009 07:13

Hi there~
What if I have more complex namespace such as :

//code-----------------------------------------------------------------------------------
//xmlns.as


namespace xmlns = "http://www.garmin.com/xmlschemas/GarminDevice/v2, http://www.w3.org/2001/XMLSchema-instance";" rel="nofollow">http://www.w3.org/2001/XMLSchema-instance";

//in your xml reading class
use namespace xmlns;

var example3:XML =

<Device xmlns="http://www.garmin.com/xmlschemas/Device/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.Tool.com/xmlschemas/Device/v2 www.Tool.com/xmlschemas/Devicev2.xsd">

<Child>This is the child</Child>
</Device> ;
trace(example3.Child); // traces 'This is the child'

//code-----------------------------------------------------------------------------------


thanks ~~

Hugo

November 21. 2009 22:02

Tks a lot, u saved my skin!

marcelo

Comments are closed