Documentation for the BGX Serialization classes (Flash MX 2004) Version 1.4.1  2005-02-10


Overview


Introduction

The BGX Serialization classes allow you to convert any XML object into a multi level actionscript object (deserialization), and vice versa to convert a complex actionscript object into XML (serialization). To achieve this two separate classes are provided: BgxDesObject and BgxSerObject.

The BgxDesObject class is in many ways similar to the XML Connector component provided by Macromedia, albeit less potent in data typing. It does not support schemas and data formatting. However, it does always reliably convert all elements of an XML document into arrays of objects with the XML attributes defined as the properties of those objects. If you are comfortable with scripting this complex object can be used to bind data to UI components like the DataGrid, Combos and Lists with very little effort.

The complex object can further be used as a global data container (DataHolder if you want) of an application in which each property can be changed when needed, new properties can be added etc. To save the data the whole object or parts of it can be serialized again and sent back to the server, containing the modifications.

The BgxSerObject class on the other hand converts complex actionscript objects with n-level arrays of objects instantly into XML which can be accessed either as XML object or as XML string that could e.g. be sent to a server.

back to top

 


Deployment

Use the supplied MXP file to install the classes at the following location $flash/Classes/bgx/ whereby $flash/Classes is by default:

  • Windows 2000 or Windows XP: C:\Documents and Settings\user\Local Settings\ Application Data\Macromedia\Flash MX 2004\language\Configuration\classes
  • Windows 98: C:\Windows\Application Data\Macromedia\Flash MX 2004\ language\Configuration\classes
  • Macintosh OS X: Hard Drive/Users/Library/Application Support/Macromedia/Flash MX 2004/language/Configuration/classes

The MXP file will make the documentation available in the Flash Help Panel and also populates the Actions Panel with the actions for the classes.

If you prefer you don't have to install the classes at the absolute class path location (or run the MXP file to install the Documentation and then remove the classes) but deploy them instead only with specific projects by copying the bgx folder that contains the class files into the same folder that contains your .fla files. (Note: if you use several folders with .fla files you have to copy the bgx folder into each one of them.)

If this is new to you please read "Understanding the classpath" in the Flash MX 2004 Actionscript Reference Guide.

To use the classes within your Flash files you have to import them, using either:

import bgx.BgxDesObject;
import bgx.BgxSerObject;

to reference the classes individually or:

import bgx.*;

to import all the classes deployed in the bgx folder.

For further information on importing classes see "Importing classes" in the Flash MX 2004 Actionscript Reference Guide.

back to top

 

 


Reference

BgxDesObject class

BgxSerObject class

 

 


Understanding the BgxDesObject class

Parsing XML with the BgxDesObject class

To understand what the BgxDesObject class does lets have a look at some random XML that contains all the aspects we need to demonstrate the features of the class.

Example XML:

<?xml version="1.0" encoding="UTF-8"?>
<siteRoot xmlns:bgx="urn:schemas-bgx-samplexml" label="bgx:components" description="bgx:components">
    <bgx:comment description="Description of site structure bgx:components"/>
    <page label="home page" URL="http://www.bgxcomponents.com/"/>
    <folder label="Web Components">
        <page label="ASP.NET Proxy Webservice (GlobalWeather)" URL="http://www.bgxcomponents.com/getWeatherWS.htm"/>
        <page label="BGX SimpleCounter(ASP.NET/ASP)" URL="http://www.bgxcomponents.com/bgxSimpleCounter.htm"/>
    </folder>
    <folder label="Tutorials &amp; Samples">
        <folder label="Weather webservice">
            <page label="Introduction" URL="http://www.bgxcomponents.com/weatherWebservice.htm"/>
            <page label="Flash client" URL="http://www.bgxcomponents.com/flashWeatherClient.htm"/>
            <page label="ASP.NET proxy Webservice" URL="http://www.bgxcomponents.com/aspnetWeatherProxy.htm"/>
            <page label="ASP.NET client" URL="http://www.bgxcomponents.com/aspnetWeatherClient.htm"/>
        </folder>
    </folder>
    <exampleNode>Some node text here.</exampleNode>
</siteRoot>

To use the data in Flash it would have to be loaded into an XML object first. E.g. if the XML resides in a file called sample.xml you might use the following:

//load xml from external file
var sampleXML:XML = new XML();
sampleXML.ignoreWhite = true;
sampleXML.load("sample.xml");

To create a mutli-dimensional object starting with the root node of that sample you can now use e.g.:

//global variable to hold deserialized sample data
var SampleData:Object;

var rootNode:XMLNode = sampleXML.firstChild;
SampleData = new BgxDesObject();
SampleData.xmlNode = rootNode;
SampleData.parse();

reference overview    back to top

Accessing parsed data

After that all elements of the XML will be accessible as arrays of objects with the XML attributes defined as the properties of those objects. The attributes of the root node itself will be direct properties of the BgxDesObject instance. You can e.g. access the label of the root node in our XML example as:

SampleData.label;

You could list all the labels of the first level folders in a text field called tbxDisplay as follows:

tbxDisplay.text = "First level folders:\n";
for (var i = 0; i < SampleData.folder.length; i++)
{
    tbxDisplay.text += " " + SampleData.folder[i].label + "\n";
}

The URL of the page labeled Flash client would be accessible as:

SampleData.folder[1].folder[0].page[1].URL;

etc.

reference overview    back to top

Accessing text from text nodes

Text data from text nodes will be added to the object representing the element as a property called nodeText. Thus the text of the exampleNode is accessible as:

SampleData.exampleNode[0].nodeText;

Note: Even though there is only one exampleNode element the BgxDesObject class will always represent it as array. So you have to use the indexer [] to access the element data.

reference overview    back to top

Nodes with namespace declaration

The XML example above contains a node with the nodename bgx:comment which in this sample does not make much sense, but is enough to demonstrate how the BgxDesObject class handles node names with namespace declarations which would be common for most XML that is generated directly by database queries or returned by webservices.

Following the logic demonstrated above the bgx:comment would produce an array called bgx:comment. However, as colons are not permitted in Actionscript property names the BgxDesObject class by default substitutes the colon with "_cln_". Thus the description attribute of that element is actually accessible as:

SampleData.bgx_cln_comment[0].description;

Similarly the namespace declaration attribute in the root node will be available as:

SampleData.xmlns_cln_bgx;

If you use the BgxSerObject class to re-serialize the SampleData object, "_cln_" will again be replaced with ":", resulting in the correct XML node or attribute name.

Note: Colon substitution can be switched off by setting the replaceColon property to false, in which case only the part of the name after the colon will be used. In the examples above this would result in the following property names:

SampleData.comment;

SampleData.bgx;

Likewise can the colon substitution string be changed to any other string that will produce valid property names by changing the value of the colonSubst property.

reference overview    back to top

 

Cloning complex Objects

Why cloning?

Assume the following scenario: You have loaded some XML data and bound it to a DataGrid or a List etc. Now you want to allow users to change some of that data via some editable DataGrid without applying the changes immediately to the original Object.

If you simply use e.g.
var myNewArray = SampleData.folder[1].folder[0].page;
myEditableDataGrid.dataProvider = myNewArray;
you just create a reference to the Object in SampleData, not a copy of it.

Any changes you would make would immediately be reflected in SampleData.

For a sample application check http://www.bgxcomponents.com/xmlSerCloning.htm.

The clone() method, however, creates not only a reference to the original object but a real copy of the Object itself and all child Objects and Arrays.

You can eithr clone an entire instance of a BgxDesObject Class itself by simply calling
instanceBgxDesObject
.clone();

or clone any other complex Object or Array that you pass like
instanceBgxDesObject.clone(instanceBgxDesObject.child[0].property);
instanceBgxDesObject.clone(dgPagesCloned.dataProvider);

You can pass either Arrays or Objects to the clone() function and it will return respectively an Array or an Object.

All Objects within the cloned Data will be of type BgxDesObject and will include automatically a reference to the respective parentNodes within the cloned data. E.g. the following

var ClonedData = SampleData.clone();
trace (ClonedData.folder[1].folder[0].parentNode.label);

will return "Tutorials & Samples".

You can also pass an identifier for the parent of the cloned Object itself e.g. to link it back into a BgxDesObject, like in the sample mentioned the following

SampleData.folder[1].folder[0].page = SampleData.clone(dgPagesCloned.dataProvider,SampleData.folder[1].folder[0]);
trace(SampleData.folder[1].folder[0].page[0].parentNode.label);

will return "Weather webservice".

Note: As the Serialization Classes are mainly set up to deal with XML compliant data structures and to avoid entering in recursive loops without exit, properties of Objects which are Objects themselves (i.e. they are not Arrays or simple types like Strings, Numbers, Boolean) will not be included in the clone. E.g. a lone of the following Object

var testObj = new Object();
testObj["id"] = 1;
testObj["isNew"] = true;
testObj["name"] = "test";
testObj["dataObj"] ={val1:1,val2:2};
testObj["dataArray"] = [{val1:1,val2:2},{val1:3,val2:4}];

will not include the property dataObj.

 

reference overview    back to top

 

 

 


Properties

Property Value (defaults in bold) Description
xmlNode
XML Node
The node of an XML object at which parsing shall start.
replaceColon
Boolean
Default: true

If set to true colons in attribute or element names will be replaced with the value of the colonSubst property.

If set to false only the part of the element name after the colon will be used.

colonSubst

String
Default: "_cln_"

Specifies the string with which to replace colons in attribute or element names if the replaceColon property is set to true.
parsed Boolean, read only true after a parse() call is successfully executed.
includeNodeName Boolean
Default: true

If set to true a property called nodeName is added to each object representing an Xml element containing the element name.

includeParentReference Boolean
Default: true

If set to true a property called parentNode is added to each object representing an Xml element that refers back to the object representing the parent Xml node.

E.g. in the exmple above SampleData.folder[0].page[1].label
will return
"ASP.NET Proxy Webservice (GlobalWeather)"
.
To retrieve the lable of the parent node of page you could use
SampleData.folder[0].label or
SampleData.folder[0].page[1].parentNode.label

If you have assigned a certain object to another variable, e.g.
var myPages:Array = SampleData.folder[0].page;
you can use e.g.
myPages[0].parentNode.label

which will return "Web Components"

numericFields
String
Default: ""

Simple data typing option. All attributes in the XML with names submitted in format  "#attributeName1#attributeName2#" etc will be typed as Numbers.

E.g. if you use
instanceBgxDesObject.numericFields = "#width#height#";
all values for width and height attributes will be defined as Numbers. All other attribute values will be defined as Strings. Any data typing (e.g. as Date, Time etc,..) will have to be done when the value is accessed.

reference overview    back to top

 


Methods

Method Parameters Description

clone()
clone(object:Object [,parent:Object])

object:Object
Object or Array to clone, if omitted the BgxDesObject instance itself will be cloned.

parent:Object
Optional identifier for the parent of the cloned Object

Returnes anew instance of the submitted Object or Array.
parse()
none
Initiates the parsing of the XMLNode set as xmlNode property of the BgxDesObject class instance.

reference overview    back to top


Events

Method Parameters Description
onParsed()
none

Event handler; invoked when an BgxDesObject instance is successfully parsed.

The default implementation of this method is not active. To override the default implementation, you must assign a function containing your own actions.

Example:

var rootNode:XMLNode = sampleXML.firstChild;
SampleData = new BgxDesObject();
SampleData.xmlNode = rootNode;
SampleData.onParsed = setDisplay;
SampleData.parse();

function setDisplay()
{
    //get the site name
    tbxDisplay.text = "Site name: " +     SampleData.label;
}

reference overview    back to top

 


Basic deserialization example

This example corresponds with the file XmlExample.fla that is supplied with the component. The following code loads the XML file sample.xml, parses it using the BgxDesObject class and then accesses some of the properties to populate a text box called tbxDisplay. The XML corresponds with the one described at Parsing XML with the BgxDesObject class.

//import the class
import bgx.BgxDesObject;

//global variable to hold deserialized sample data
var SampleData:Object;

//load xml from external file
var sampleXML:XML = new XML();
sampleXML.ignoreWhite = true;
sampleXML.onLoad = parseSampleData;
sampleXML.load("sample.xml");

//parse sample data
function parseSampleData() {
    var rootNode:XMLNode = sampleXML.firstChild;
    SampleData = new BgxDesObject();
    SampleData.xmlNode = rootNode;
    SampleData.onParsed = setDisplay;
    SampleData.parse();
}

function setDisplay(){
    //get the site name
    tbxDisplay.text = "Site name: " + SampleData.label + "\n\n";
    //get first level folders
    tbxDisplay.text += "First level folders:\n";
    for (var i = 0; i < SampleData.folder.length; i++)
    {
        tbxDisplay.text += " " + SampleData.folder[i].label + "\n";
    }
    //get the description from the bgx:comment element
    tbxDisplay.text += "\nComment:\n";
    tbxDisplay.text += SampleData.bgx_cln_comment[0].description + "\n";
    //get the namespace declaration from the root element
    tbxDisplay.text += "\nCustom namespace:\n";
    tbxDisplay.text += SampleData.xmlns_cln_bgx + "\n";
    //display text from the exampleNode text node
    tbxDisplay.text += "\nText node example:\n";
    tbxDisplay.text += SampleData.exampleNode[0].nodeText;
}

reference overview    back to top

 


Binding data to the Macromedia DataGrid Component example

This example corresponds with the file DatagridExample.fla that is supplied with the component. The following code loads the XML file sample.xml, parses it using the BgxDesObject class and then displays the page label and URL of the pages within the Weather webservice folder in an instance of the DataGrid component called dgPages. The XML corresponds with the one described at Parsing XML with the BgxDesObject class.

//import the class
import bgx.BgxDesObject;

//global variable to hold deserialized sample data
var SampleData:Object;

//load xml from external file
var sampleXML:XML = new XML();
sampleXML.ignoreWhite = true;
sampleXML.onLoad = parseSampleData;
sampleXML.load("sample.xml");

//parse sample data
function parseSampleData() {
    var rootNode:XMLNode = sampleXML.firstChild;
    SampleData = new BgxDesObject();
    SampleData.xmlNode = rootNode;
    SampleData.onParsed = populateGrid;
    SampleData.parse();
}

function populateGrid(){
    //identify the pages in the "Weather webservice" folder as the data
    //to be bound to the grid
    var pagesArray = SampleData.folder[1].folder[0].page;
    //identify the attributes that shall appear in the columns
    dgPages.columnNames= ["label", "URL"];
    //define some display parameters
    dgPages.getColumnAt(0).width = 170;
    dgPages.getColumnAt(0).headerText = "Page";
    dgPages.getColumnAt(1).headerText = "URL";

    //define an event listener that loads the page URL
    //when a row is clicked upon.
    var dgListener = new Object();
    dgListener.cellPress = function(event) {
        //you can use the itemIndex that is submitted by the event
        //to identify the page data within the SampleData Object
        var itemData = pagesArray[event.itemIndex];
        //you could also use:
        //var itemData = SampleData.folder[1].folder[0].page[event.itemIndex];
        //var itemData = dgPages.dataProvider[event.itemIndex];
        getURL(itemData.URL);
    };
    dgPages.addEventListener("cellPress", dgListener);

    //lets sort the data on the page name before binding it
    pagesArray.sortOn("label");
    //bind the data
    dgPages.dataProvider = pagesArray;
}

Note: In this example the local variable pagesArray is assigned to SampleData.folder[1].folder[0].page and later defined as dgPages.dataProvider. This means that there are now three different ways to access the very same data with the connection to the SampleData object always alive. This means e.g. if you use the local variable to change a value like

pagesArray[1].label = "Datatest";

also SampleData.folder[1].folder[0].page[1].label will now have the value "Datatest". This way you can build handy "DataHolders" to access and modify data, but when you want to save the changes you could simply use the BgxSerObject class to re-serialize the SampleData object which will produce an XML document reflecting all the changes you made.

reference overview    back to top

 


Complex Tree and DataGrid example

This example corresponds with the file TreeExample.fla that is supplied with the component. The following code loads the XML file sample.xml, parses it using the BgxDesObject class and then populates an instance of the Macromedia Tree component called bgxTree with the folder and page nodes of the XML.

It assigns click actions that display the label name and an active hyperlink in case of page nodes, a DataGrid with the list of child pages in case od folder nodes.

It further assigns double-click actions that expand/collapse folder nodes and load the associated page for page nodes.

The XML corresponds with the one described at Parsing XML with the BgxDesObject class.

Note: The Tree component allows very easy population of a tree by simply binding the XML directly to it, with XML elements containing label, data and isBranch attributes. Apart from the fact that it might not suit you to have those attributes in the XML or it would mean previous recursive parsing of the XML to add them, you cannot add complex data as treeNode data via a data attribute. The code below adds the node objects themselves as treeNode data. Therefore, if a node is clicked all data associated with that node is instantly available (see the line var newNode = treeNode.addTreeNode(nodeName,elementsArray[i]);)

Note also that within the setDisplay() function the nodeName property, added automatically if addNodeName is set to true, is used to determine whether a treeNode corresponds to an element of type folder (see  if (dataObject.nodeName == "folder")).

The following is only one way how a tree can be populated. It will depend on the actual structure of the XML data or other parameters, like what kind of interaction is needed, do determine the best route on a case by case basis.

//import the class
import bgx.BgxDesObject;

//hide DataGrid
dgPages._visible = false;

//global variable to hold deserialized sample data
var SampleData:Object;
initDisplay();

//load xml from external file
var sampleXML:XML = new XML();
sampleXML.ignoreWhite = true;
sampleXML.onLoad = parseSampleData;
sampleXML.load("sample.xml");

//parse sample data
function parseSampleData() {
    var rootNode:XMLNode = sampleXML.firstChild;
    SampleData = new BgxDesObject();
    SampleData.xmlNode = rootNode;
    SampleData.onParsed = populateTree;
    SampleData.parse();
}

function populateTree(includeRoot:Boolean)
{
    //Variation 1: add all pages and folders below the root node
    addTreeNodes(SampleData,bgxTree);
    //Variation 2: start with the site root and add all pages
    //and folders beneath it
    //var newNode = bgxTree.addTreeNode( SampleData.label, SampleData);
    //addTreeNodes(SampleData,newNode);
}

function addTreeNodes(elements:Object,treeNode:XML)
{
    for (var element in elements)
    {
        //get the elements of the original XML, which are arrays within the parsed
        //SampleData and therefore of type "object"
        //also filter out "bgx_cln_comment" and "exampleNode"
        if (typeof elements[element] == "object" &&
            element != "bgx_cln_comment" &&
            element != "exampleNode")
        {
            //loop through the elements array to add each item as tree node
            var elementsArray = elements[element];
            for (var i = 0; i < elementsArray.length; i++)
            {
                //use the label property as nodeName
                var nodeName = elementsArray[i].label;

                //add the node to the tree, setting the whole object as its data
                var newNode = treeNode.addTreeNode(nodeName,elementsArray[i]);

                //make sure that folder nodes appear as branches, even if they
                //don't have further children in the XML
                var isBranch = (element == "folder");
                bgxTree.setIsBranch(newNode,isBranch);

                //recursive call to add child nodes
                addTreeNodes(elementsArray[i],newNode);
            }
        }
    }
}

function initDisplay()
{
    //assign tree change event to setDisplay()
    treeListenerObject = new Object();
    treeListenerObject.change = function(evtObject){
        setDisplay(bgxTree.selectedNode,evtObject.target.selectedItem.attributes.data);
    }
    bgxTree.addEventListener("change", treeListenerObject);

    //identify the attributes that shall appear in the DataGrid columns
    dgPages.columnNames= ["label", "URL"];
    //define some display parameters
    dgPages.getColumnAt(0).width = 170;
    dgPages.getColumnAt(1).width = 320;
    dgPages.getColumnAt(0).headerText = "Pages";
    dgPages.getColumnAt(1).headerText = "URL";

    //define an event listener that loads the page URL
    //when a row is double-clicked.
    var dgListener = new Object();
    dgListener.cellPress = function(event) {
        //you can use the itemIndex that is submitted by the event
        //to identify the page data within the SampleData Object
        var itemData = dgPages.dataProvider[event.itemIndex];
        if (checkDblClick(itemData)) getURL(itemData.URL,"_blank");
    };
    dgPages.addEventListener("cellPress", dgListener);
}

function setDisplay(treeNode,dataObject)
{
    //double-click action
    if (checkDblClick(dataObject))
    {
        //load pages if the have an URL
        if (typeof dataObject.URL != "undefined")
        {
            getURL(dataObject.URL,"_blank");
        }
        //toggle branches on double-click
        if (bgxTree.getIsBranch(treeNode)) bgxTree.setIsOpen(treeNode,!bgxTree.getIsOpen(treeNode));
    }
    //set display
    itemTitle.text = dataObject.label;
    //display pages in the DataGrid for folders
    if (dataObject.nodeName == "folder")
    {
        dgPages.dataProvider = dataObject.page;
        dgPages._visible = true;
        itemURL.text = "";
    }
    else
    {
        dgPages._visible = false;
    }
    //display the URL as Hyperlink for pages
    if (dataObject.nodeName != "page")
    {
        itemURL.text = "";
    }
    else
    {
        itemURL.htmlText = "<a href='" + dataObject.URL + "' target='_blank'><u>" + dataObject.URL + "</u></a>";
    }
}

//----Utility double-click
//global variables
var lastClick = 0;
var lastSelected;

//check if an object was double-clicked
function checkDblClick(pObj):Boolean
{
    var clickTime = getTimer();
    var dClick = ((clickTime-lastClick<400) && (lastSelected == pObj));
    lastClick = clickTime;
    lastSelected = pObj;
    return dClick;
}
//----End utility double-click

reference overview    back to top

 


Understanding the BgxSerObject class

The BgxSerObject class allows you to convert complex Actionscript objects, like the ones created with the BgxDesObject class, into XML with very little effort. It makes the XML available both as simple XML string, that could be sent to the server as value of a variable, and as XML object that can be used as such in Flash.

See

for some code examples.

reference overview    back to top

 

Serializing objects

To serialize an object you have first to define an object as sourceObject of an instance of the BgxSerObject class and then call the serialize() method as shown below:

//import the class
import bgx.BgxSerObject;

//global variables to hold data
var SerObj:Object;

//create complex object

//create an array
var myArray:Array = new Array();
//add objects
for (var i = 0; i < 5; i++)
{
    var obj = new Object();
    //add attributes
    obj["att1"] = "first value - " + i;
    obj["att2"] = "second value - " + (i * 3);
    myArray.push(obj);
}

//create root object and add attributes
var SampleData:Object = new Object();
SampleData["label"] = "Test object";
SampleData["childNode"] = myArray;

//serialize the object
SerObj = new BgxSerObject();
SerObj.sourceObject = SampleData;
SerObj.serialize();

This will produce the following XML:

<?xml version="1.0" encoding="utf-8" ?>
<ROOT label="Test object">
    <childNode att2="second value - 0" att1="first value - 0"></childNode>
    <childNode att2="second value - 3" att1="first value - 1"></childNode>
    <childNode att2="second value - 6" att1="first value - 2"></childNode>
    <childNode att2="second value - 9" att1="first value - 3"></childNode>
    <childNode att2="second value - 12" att1="first value - 4"></childNode>
</ROOT>

reference overview    back to top

 

Setting the root name

While all element and attribute names will be automatically generated using the property names od the sourceObject, the BgxSerObject class cannot automatically detect the name you would like to give the XML root node. Therefore the default root name is ROOT, but you can use the rootName property to set it to any other string value that would result in a valid element name, like:

bgxSerObjectinstance.rootName = "myName";

reference overview    back to top

Excluding XML declaration

By default the XML produced by the BgxSerObject class contains an XML declaration, but you can set the includeDeclaration property to false to produce XML without declaration.

bgxSerObjectinstance.includeDeclaration = false;

reference overview    back to top

 

Excluding properties

By default the XML produced by the BgxSerObject class contains all properties found in the submitted object, but you can use the excludedProperties property to submit property names that will not be included in the XML output, like:

bgxSerObjectinstance.excludedProperties = "#att1#att2#";

Note: You cannot exclude e.g. a property named att1 on one type of object and include it on another one. The submitted property names will be applied globally.

reference overview    back to top

Character encoding

The BgxSerObject class will automatically HTMLencode the following characters, as they would produce invalid XML if not encoded:

Character Encoded
<
&lt;
> &gt;
& &amp;
" &quot;

 

 

 

 

reference overview    back to top

 

Handling namespace declarations

Actionscript property names cannot include colons but you might need to colons in your XML attribute and element names. The BgxSerObject class contains a property called colonSubst that contains a string that should be replaced with colon when found in an attribute name. By default this string is "_cln_" but you can change it to any other string value.

Using the default value a property called e.g. bgx_cln_comment will appear as bgx:comment in the XML.

See also Nodes with namespace declaration in the documentation for the BgxDesObject class.

reference overview    back to top

 

Handling of property called "nodeName"

The BgxDesObject class will add a property called nodeName to each object that is not originally an XML attribute. Therefore the BgxSerObject class excludes that property from the XML by default. You can include it though by setting the excludeNodeNameAttribute property to false.

reference overview    back to top

 

Handling of property names beginning with "__"

Private properties conventionally are named using two underscores at the beginning of the property name, like e.g. __validated. The BgxSerObject class automatically excludes all properties with names that start with two underscores.

reference overview    back to top

 

Accessing the XML as String

Use the xmlString property to retrieve the XML after serializing as a single XML string, like

var output:String = bgxSerObjectinstance.xmlString;

reference overview    back to top

 

Accessing the XML as XML

Use the getXML() method to retrieve the XML after serializing as a single XML, like

var output:XML = bgxSerObjectinstance.getXML();

reference overview    back to top

 

 


Properties

Property Value (defaults in bold) Description
sourceObject
Object
The Object to be serialized.
colonSubst

String
Default: "_cln_"

Specifies the string which shall be replaced with colon in property names.
serialized Boolean, read only true after a serialize() call is successfully executed.
includeDeclaration Boolean
Default: true
If set to true the XML declaration will be added to the XML output.
rootName
String
Default: "ROOT"

String defining the name of the XML root element .

excludedProperties String
Default: ""

String in format "#propertyName1#propertyName2#" identifying properties to be excluded from the XML.

Note: You cannot exclude e.g. a property named att1 on one type of object and include it on another one. The submitted property names will be applied globally.

excludeNodeNameAttribute Boolean
Default: true

If set to true properties called nodeName will not be included in the XML.

This property exists in particular to remove the nodeName property the BgxDesObject class will by default add to each object to identify the original XML element name.

xmlString String, read only The XML in string format, available after calling the serialize() method.

reference overview    back to top

 


Methods

Method Parameters Description
serialize()
none
Initiates the serializing of the Object set as sourceObject property of the BgxSerObject class instance.

reference overview    back to top

 


Events

Method Parameters Description
onSerialized()
none

Event handler; invoked when an BgxSerObject instance is successfully serialized.

The default implementation of this method is not active. To override the default implementation, you must assign a function containing your own actions.

Example:

SerObj = new BgxSerObject();
SerObj.sourceObject = SampleData;
SerObj.onSerialized = setDisplay;
SerObj.serialize();

function setDisplay()
{
    tbxDisplay.text = SerObj.xmlString;
}

reference overview    back to top

 


Serializing objects created with the BgxDesObject class

This example corresponds with the file SerializationExample.fla that is supplied with the component. The following code loads the XML file sample.xml, parses it using the BgxDesObject class and then uses an instance of the BgxSerObject class to re-serialize it using the default settings, displaying the XML string created in a text field called tbxDisplay and accesses the XML as XML to extract the label attribute from the root element, displayed in the text field tbxRootLabel.

It furthermore sets the value of the text boxtbxRootname as the root name of the XML and the value of the text box tbxRootLabel as the value of SampleData.label when the button btnSerialize is clicked, and then re-serializes the data.

The XML corresponds with the one described at Parsing XML with the BgxDesObject class.

//import the classes
import bgx.BgxDesObject;
import bgx.BgxSerObject;

//global variables to hold data
var SampleData:Object;
var SerObj:Object;

//load xml from external file
var sampleXML:XML = new XML();
sampleXML.ignoreWhite = true;
sampleXML.onLoad = parseSampleData;
sampleXML.load("sample.xml");

//parse sample data
function parseSampleData() {
    var rootNode:XMLNode = sampleXML.firstChild;
    SampleData = new BgxDesObject();
    SampleData.xmlNode = rootNode;
    SampleData.onParsed = serialize;
    SampleData.parse();
}

function serialize(pRootName:String)
{
    SerObj = new BgxSerObject();
    if (typeof pRootName != "undefined")
    {
        SerObj.rootName = pRootName;
    }
    SerObj.sourceObject = SampleData;
    SerObj.onSerialized = setDisplay;
    SerObj.serialize();
}

function setDisplay()
{
    tbxDisplay.text = SerObj.xmlString;
    var serXml:XML = SerObj.getXML();
    tbxRootLabel.text = serXml.firstChild.attributes["label"];
}

btnSerialize.onRelease = function()
{
    if (tbxRootlabel.text != "")
    {
        SampleData.label = tbxRootlabel.text;
    }
    if (tbxRootname.text != "")
    {
        serialize(tbxRootname.text);
    }
}

reference overview    back to top

 


Serializing general complex objects example

This example corresponds with the file SerializationExample.fla that is supplied with the component. The following code first creates a custom complex object and then an instance of the BgxSerObject class to serialize it using the default settings, displaying the XML string created in a text field called tbxDisplay and accesses the XML as XML to extract the label attribute from the root element, displayed in the text field tbxRootLabel.

It furthermore sets the value of the text box tbxRootname as the root name of the XML and the value of the text box tbxRootLabel as the value of SampleData.label when the button btnSerialize is clicked, and then re-serializes the data.

//import the class
import bgx.BgxSerObject;

//global variables to hold data
var SerObj:Object;

//create complex object

//create an array
var myArray:Array = new Array();
//add objects
for (var i = 0; i < 5; i++)
{
    var obj = new Object();
    //add attributes
    obj["att1"] = "first value - " + i;
    obj["att2"] = "second value - " + (i * 3);
    myArray.push(obj);
}

//create root object and add attributes
var SampleData:Object = new Object();
SampleData["label"] = "Test object";
SampleData["childNode"] = myArray;

serialize();

function serialize(pRootName:String)
{
    SerObj = new BgxSerObject();
    if (typeof pRootName != "undefined")
    {
        SerObj.rootName = pRootName;
    }
    SerObj.sourceObject = SampleData;
    SerObj.onSerialized = setDisplay;
    SerObj.serialize();
}

function setDisplay()
{
    tbxDisplay.text = SerObj.xmlString;
    var serXml:XML = SerObj.getXML();
    tbxRootLabel.text = serXml.firstChild.attributes["label"];
}

btnSerialize.onRelease = function()
{
    if (tbxRootlabel.text != "")
    {
        SampleData.label = tbxRootlabel.text;
    }
    if (tbxRootname.text != "")
    {
        serialize(tbxRootname.text);
    }
}

This will produce the following XML:

<?xml version="1.0" encoding="utf-8" ?>
<ROOT label="Test object">
    <childNode att2="second value - 0" att1="first value - 0"></childNode>
    <childNode att2="second value - 3" att1="first value - 1"></childNode>
    <childNode att2="second value - 6" att1="first value - 2"></childNode>
    <childNode att2="second value - 9" att1="first value - 3"></childNode>
    <childNode att2="second value - 12" att1="first value - 4"></childNode>
</ROOT>

reference overview    back to top

 

 

© 2004 Bernhard Gaul Documentation version 2005-02-10