Sunday 14 August 2011

Quick Tip: Checking for XML nodes with a namespace

This is a small follow up to Common Mistakes: XML Namespaces and E4X: when working with namespaces, calling hasOwnProperty() may not work as expected. Consider the following example:

var xml: XML = <root xmlns:space="http://www.something.com">
 <space:tag>
  <node>Hello, world!</node>
 </space:tag>
</root>;

trace( xml.hasOwnProperty( "tag" ) );

In this case, hasOwnProperty() will return false as the 'tag' tag is part of the 'space' namespace. In order to overcome this, use the QName construct, e.g.:

xml.hasOwnProperty( new QName( "http://www.something.com", "tag" ) )

Alternatively, if you have declared a namespace previously, you can do the following:

namespace space = "http://www.something.com"; 

// ...

xml.hasOwnProperty( new QName( space, "tag" ) )

No comments:

Post a Comment