Parsing XML nodes and Objects with dashes in their names in ActionScript 3.0

The following example shows how you can parse an XML node with a dash in its node name (<font-family />) as well as parsing an Object with a dash in it’s identifier using the square bracket notation ([]).

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/28/parsing-xml-nodes-and-objects-with-dashes-in-their-names-in-actionscript-30/ -->
<mx:Application name="XML_parser_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="horizontal"
        verticalAlign="middle"
        backgroundColor="white"
        initialize="init();">

    <mx:Script>
        <![CDATA[
            import mx.rpc.xml.SimpleXMLDecoder;
            import mx.utils.ObjectUtil;

            private function init():void {
                var obj:Object = xmlToObject(xmlDP);

                txtXML.text = xmlDP.toXMLString();
                txtObject.text = ObjectUtil.toString(obj);

                lblXML.text = xmlDP.entry.child('font-family').text();
                lblObject.text = String(obj.root.entry["font-family"]);
            }

            private function xmlToObject(value:XML):Object {
                var xmlStr:String = value.toXMLString();
                var xmlDoc:XMLDocument = new XMLDocument(xmlStr);
                var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
                var resultObj:Object = decoder.decodeXML(xmlDoc);
                return resultObj;
            }
        ]]>
    </mx:Script>

    <mx:XML id="xmlDP">
        <root>
            <entry>
                <font-family>Arial</font-family>
                <font-size>12</font-size>
                <font-weight>normal</font-weight>
                <text-decoration>underline</text-decoration>
                <text>Hello world!</text>
            </entry>
        </root>
    </mx:XML>

    <mx:Panel id="xmlPanel">
        <mx:Text id="txtXML" />
        <mx:ControlBar>
            <mx:Label text="font-family:" />
            <mx:Label id="lblXML" />
        </mx:ControlBar>
    </mx:Panel>

    <mx:Panel id="objPanel" height="{xmlPanel.height}">
        <mx:Text id="txtObject" />
        <mx:ControlBar>
            <mx:Label text="font-family:" />
            <mx:Label id="lblObject" />
        </mx:ControlBar>
    </mx:Panel>

</mx:Application>

View source is enabled in the following example.

0 thoughts on “Parsing XML nodes and Objects with dashes in their names in ActionScript 3.0

  1. How can I do escape symbols like: & ^ ” ‘ > < ? ……
    I’m trying to load data from external XML file that contains text like L&F and when the data is loaded into flash-file looks like L&F. Any help will be useful! Thanks in advance!