Handle XML with namespaces
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.
Related posts:
- Change screen orientation of a Microsoft Surface application In order to understand the need of changing the screen...
- URL shortening too long? j.mp is the answer Tinyurl.com had on its own 11 characters, bit.ly 6 characters(...
- Scripting.FileSystemObject While working on my new pet project, I encountered a...
- Change Browser’s UserAgent The question of What’s that user agent string used for?...
- PDC 2008 – Project "Velocity": A First Look PDC 2008 Velocity - the distributed caching platform. Presentation about...
Euro
Lira sterlina
Dolar SUA
Francul elvetian
Gramul de aur



