Tuesday, June 01, 2010

Gotcha Of The Day: Working with Namespaces in ActionScript XML

ActionScript 3's XML handling is pretty dang impressive. Gone are the days of manually iterating through nodes. Now, you can seamlessly access elements and attributes like any other variable.

So, you can imagine my confusion when this simple XML document wasn't behaving:

<?xml version="1.0" encoding="UTF-8"?>
  <tt xml:lang="en" xmlns="http://www.w3.org/2006/04/ttaf1"  xmlns:tts="http://www.w3.org/2006/04/ttaf1#styling">
              <p begin="00:00:00.50" dur="500ms">Hello</p>
              <p begin="00:00:1.28" dur="500ms">World</p>

I should have been able to execute:

 var doc:XML = new XML(...);
 trace("number of items: " + doc.body.div.p.length);

Instead, body was always null, causing the above expression failed.

The issue at hand turns out to be the XML namespace http://www.w3.org/2006/10/ttaf1. In order to access the various elements from the document, technically, I'd need to use their complete name -- which includes the namespace.

Some folks go as far as pre-processing the XML document and stripping out any namespaces. While tempting to do in the heat of the moment, I thought there had to be a better way.

And there is -- if you have a document with a single namespace, you can set your default namespace once and access it as you normally would.

So the above code became:

 var ns:Namespace = new Namespace("http://www.w3.org/2006/10/ttaf1");
 default xml namespace = ns;
 var doc:XML = new XML(...);
 trace("number of items: " + doc.body.div.p.length);

Problem solved, and I didn't have to do any regular expression hackery to get the job done.

No comments:

Post a Comment