Internet / Software Applications

Macromedia Flash MX 2004 ActionScript Programming Tutorial

Manipulating Data in an XML Object

You can also add data to your XML object using the createElement, createTextNode, and appendChild methods. createElement creates a new element (node), which is assigned to a variable of the XMLNode type:

var newBook = Library.createElement(“book”);

The above code creates an empty element called “book”, just like our other “books”. Once you’ve created an element, you append it to the XML object in the location where you want it within the hierarchy:

Library.firstChild.appendChild(newBook);

This appends the new element on the same level as the other “book” elements in our Library object. If we then wanted to create new “title” and “author” elements for our new “book”, we’d use the same procedure:

newTitle = Library.createElement(“title”);

newAuthor = Library.createElement(“author”);

Library.firstChild.lastChild.appendChild(newTitle);

Library.firstChild.lastChild.appendChild(newAuthor);

Finally, to fill the new elements with data, use the createTextNode method. A text node represents the value of a node, which is, in XML, another node. If we were adding a form to our movie that allows the user to add a new book, we’d create variables to store the values of the title and author text fields, and then assign those values to the text nodes to be created:

BookTitle = title_txt.text;

BookAuthor = author_txt.text;

BookTitleNodeValue = Library.createTextNode(BookTitle);

BookAuthorNodeValue = Library.createTextNode(BookAuthor);

The last two lines are equivalent to something like the following:

BookTitleNodeValue = Library.createTextNode(“My Guide to Flash Volume 3”);

BookAuthorNodeValue = Library.createTextNode(“John and Jane Doe”);

Then we’d place the text nodes in the correct location in the XML object using:

newTitle.appendChild(BookTitleNodeValue);

newAuthor.appendChild(BookAuthorNodeValue);

Remember that in the example above, newTitle and newAuthor were defined as XML nodes, which we created and whose values are undefined until now, when we’ve appended the new text nodes to them.

By using these methods inside a few more functions that employ arrays and loops, you can expand our earlier database front-end to let users add books to the XML object Library.

This is only a brief introduction to the use of XML in Flash, which can be used for much more complex communication over the Web than what we’ve demonstrated here.

Macromedia Flash MX 2004 ActionScript 2.0 Tutorial and Free Online Training Course

In this section, you learned about:

  • The Key Class
  • Using on(keypress)
  • Using getcode()
  • Using listeners
  • Using components
  • Using the LoadVars() Class
  • Using the XML class to load and manipulate XML
  • Loading an XML document
  • Displaying XML data
  • Manipulating data in an XML object