19.5. Creating an XML Object from an Array

Problem

You want to create an XML object using an array to populate it.

Solution

Use a for statement to create and insert the elements and text nodes.

Discussion

Generating an XML object, especially a large one, can be somewhat tedious. In some cases you can make your job a little easier by storing the text node values in an array and inserting them into the XML object using a for loop.

Let’s take a look at an example in which you want to create an XML object to represent a menu and the menu items. This might be a useful example if, say, you are creating a Flash movie that allows the user to configure a menu’s items and save them to the server so he can retrieve them later on.

// Include XML.as for the custom createElementWithText(  ) method from Recipe 19.4.
#include "XML.as"

// Create the array of text node values.
menuItems = new Array("Springs", "Cogs", "Widgets", "Gizmos");

my_xml = new XML(  );

// Create the root element for the XML object.
rootElement = my_xml.createElement("menu")

// Use a for statement to loop through all the elements in the array. for (var i = 0; i < menuItems.length; i++) { // Create an XML element for each arrangement. menuItemElement = my_xml.createElementWithText("menuItem", menuItems[i]); rootElement.appendChild(menuItemElement); } // Add the root element to the XML object. my_xml.appendChild(rootElement); // Displays: <menu><menuItem>Springs</menuItem><menuItem>Cogs</menuItem> // <menuItem>Widgets</menuItem><menuItem>Gizmos</menuItem></menu> ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.