Handle XML with namespaces 1


I faced an issue while working with an xml file in Flash. I was unable to parse the xml data using the normal E4X syntax such as xml.node1.node2. It would give an error. The only thing different about this particular xml is that it has a lot of namespaces declared in it. After going through the documentation I found out a way to handle this issue. Let’s consider the following code:

var xml:XML = <Workbook xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x2="http://schemas.microsoft.com/office/excel/2003/xml" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel">
  <ss:Worksheet ss:Name="Sheet1">
  <Table ss:StyleID="ta1">
    <Row ss:AutoFitHeight="0" ss:Height="13.4064">
      <Cell>
        <Data ss:Type="String">Preview</Data>
      </Cell>
      <Cell>
        <Data ss:Type="String">unicode</Data>
      </Cell>
      <Cell>
        <Data ss:Type="String">htmlcode</Data>
      </Cell>
      <Cell>
        <Data ss:Type="String">htmlalt</Data>
      </Cell>
      <Cell>
        <Data ss:Type="String">utfcode</Data>
      </Cell>
      <Cell>
        <Data ss:Type="String">utfalt</Data>
      </Cell>
    </Row>
  </Table>
  </ss:Worksheet>
</Workbook>

Usage:

namespace ns1 = "urn:schemas-microsoft-com:office:spreadsheet";
use namespace ns1;
trace(xml..*::Table.Row[0].Cell[0].Data); //Preview

Here, I just declared the default namespace for the above xml. Try this code without the namespace statement and you will get an error. The namespace declared without a prefix is the default namespace for the xml. For this xml the default namespace is xmlns=”urn:schemas-microsoft-com:office:spreadsheet”.

In this case what I’ve done is declared the default namespace in actionscript. And to reference a deeply nested node I’ve used “..*::” instead of a simple ” ..”

Also, in case you want to remove all the namespaces mentioned in the xml, you can try doing something like this:

var arNS:Array = xml.inScopeNamespaces();
for each (var item:Namespace in arNS)
{
	xml.removeNamespace(item);
}

However, do note that this will not remove the default namespace.

Leave a comment

Your email address will not be published. Required fields are marked *