Modifying XML content within Flash

Its common to load an external XML file and update the structure and contents in a Flash application. Flash has methods such as cloneNode and removeNode that change the document structure. Well look at these methods in this section.

Before we continue, however, its important to recognize the limits of the XML class when updating XML documents. Flash allows you to manipulate the document tree inside a movie, but it cant modify an external XML document.

If you need to change an external file, youll have to send the updated content from Flash to a server-side file for processing. Only server-side files have permission to update physical XML files. Well look at how you can send XML content from Flash a little later in the chapter.

The modifications that we want to make to an XML document generally fall into these categories:

  • Changing existing values

  • Duplicating existing nodes

  • Removing nodes

  • Changing node structures

Well look at each of these modifications in more detail.

Changing existing values

You can change the text or attributes associated with an XML document by assigning new values. Youll need to locate the node and enter the new value. You can also change the name of an element within Flash.

Changing a text node

If youre dealing with a text element, you can use the nodeValue property to assign updated text to the node. Remember that you can only use the nodeValue property on text nodes.

 myNode.nodeValue = "Updated value"; 

The following example loads the file address.xml and changes the value of the first <name> element to Jo Green . You can find the example in the resource file modifyXML.fla . The example doesnt update the external file, but only the document tree within Flash.

 var RootNode:XMLNode; var NameNode:XMLNode; var addressXML:XML = new XML(); addressXML.ignoreWhite = true; addressXML.onLoad=loadAddresses; addressXML.load("address.xml"); stop(); function loadAddresses(success:Boolean):Void {   if (success) {     RootNode = this.firstChild;     trace ("before: " + RootNode.firstChild);     NameNode = RootNode.childNodes[0].firstChild;  NameNode.firstChild.nodeValue = "Jo Green";  trace ("after: " + RootNode.firstChild);   } } 

When you test the code, youll see the Output window shown in Figure 4-37.

image from book
Figure 4-37: Displaying the first <name> element before and after the change

Changing an attribute value

Changing an attribute value is even easier. You assign the new value to the attribute using either of the two lines shown here. Both lines are equivalent.

 myNode.attributes.attName = "Updated value"; myNode.attributes.["attName"] = "Updated value"; 

The next example changes the value of the first contact id of the loaded file address.xml from 1 to 99 . Ive highlighted the line in bold. You can find the example in the resource file modifyXML.fla . To test the file, youll need to uncomment the code block.

 var RootNode:XMLNode; var NameNode:XMLNode; var addressXML:XML = new XML(); addressXML.ignoreWhite = true; addressXML.onLoad=loadAddresses; addressXML.load("address.xml"); stop(); function loadAddresses(success:Boolean):Void {   if (success) {     RootNode = this.firstChild;     trace ("before: " + RootNode.firstChild);  RootNode.firstChild.attributes.id = "99";  trace ("after: " + RootNode.firstChild);   } } 

Figure 4-38 shows the Output window that displays when you test this code.

image from book
Figure 4-38: Displaying the <contact> element before and after the change

Changing a node name

You dont often need to change the name of a node in an XML document tree. External applications using the XML document often rely on a fixed set of XML tag names, which means changing the names within Flash may cause errors. If you need to change tag names , however, you can use the nodeName property:

 myNode.nodeName = "New tag name"; 

Note that you can only change the name of element nodes as text nodes dont have names.

The next example loops through all <name> elements from the address.xml file and changes them to <fullName> elements. Ive highlighted the relevant line in bold. You can find the code in the resource file modifyXML.fla . Again, you may need to uncomment the relevant code blocks within Flash to test the file.

 var RootNode:XMLNode; var NameNode:XMLNode; var addressXML:XML = new XML(); addressXML.ignoreWhite = true; addressXML.onLoad=loadAddresses; addressXML.load("address.xml"); stop(); function loadAddresses(success:Boolean):Void {   if (success) {     RootNode = this.firstChild;     for (var i:Number=0; i<RootNode.childNodes.length; i++) {       NameNode = RootNode.childNodes[i].firstChild;       trace ("before: " + NameNode);  NameNode.nodeName = "fullName";  trace ("after: " + NameNode);     }   } } 

When you test the code, youll see something similar to Figure 4-39.

image from book
Figure 4-39: Displaying changes to the <name> element

Duplicating an existing node

If you need to add a new node, a useful technique is to duplicate an existing node and change the values. When you duplicate a node, you can choose whether to duplicate the child nodes as well. This can save a lot of time when youre working with complicated node structures.

The cloneNode method allows you to duplicate a node. It takes one argument, deep , a Boolean value, that is, true or false, indicating whether or not to include the child nodes. A cloned node doesnt have a position within the document tree. Once you have cloned a node, youll need to insert it into the document tree with either the appendChild or the insertBefore method.

The following code demonstrates how to clone a node with all of its children and append it to another node:

 var myNewNode:XMLNode = myOldNode.cloneNode(true); myParentNode.appendChild(myNewNode); 

You could also have inserted it before an existing node:

 var myNewNode:XMLNode = myOldNode.cloneNode(true); RootNode.insertBefore(myNewNode, myParentNode); 

The next example shows how you could duplicate a <contact> node from the address.xml file and change the values. You can see the example saved in the resource file cloneXML.fla .

 var RootNode:XMLNode; var ContactNode:XMLNode; var addressXML:XML = new XML(); addressXML.ignoreWhite = true; addressXML.onLoad=loadAddresses; addressXML.load("address.xml"); stop(); function loadAddresses(success:Boolean):Void {  if (success) {    RootNode = this.firstChild;    ContactNode = RootNode.firstChild;  var NewContactNode:XMLNode = ContactNode.cloneNode(true);   NewContactNode.attributes.id = "4";   NewContactNode.childNodes[0].firstChild.nodeValue = "Mark Brown";   NewContactNode.childNodes[1].firstChild.nodeValue = "Hot country";   NewContactNode.childNodes[2].firstChild.nodeValue = "999 999";   RootNode.appendChild(NewContactNode);  trace (this);  } } 

In the previous example, we cloned the first <contact> node and appended it after the last <contact> node. We then changed the values to produce the following XML fragment at the end of the XML document tree:

 <contact id="4">   <name>Mark Brown</name>   <address>Hot country</address>   <phone>999 999</phone> </contact> 

Figure 4-40 shows the Output window that displays when you test the code.

image from book
Figure 4-40: Displaying the cloned <contact> element

You may also need to delete an element from your XML document tree.

Deleting existing content

The removeNode method allows you to remove a node from the document tree within Flash. As with all of the other modification methods, these changes only affect the tree inside Flash and wont automatically update an external XML document.

 myNode.removenode(); 

When you remove a node from the document tree, all child nodes and other descendants are removed at the same time.

The next example shows how you can remove the last <contact> element from the loaded address.xml file. You can see this example in the resource file removeXML.fla .

 var RootNode:XMLNode; var ContactNode:XMLNode; var addressXML:XML = new XML(); addressXML.ignoreWhite = true; addressXML.onLoad=loadAddresses; addressXML.load("address.xml"); stop(); function loadAddresses(success:Boolean):Void {   if (success) {     RootNode = this.firstChild;     ContactNode = RootNode.lastChild;     trace ("before: " + RootNode.lastChild);  ContactNode.removeNode();  trace ("after: " + RootNode.lastChild);   } } 

Figure 4-41 shows the resulting Output window when we test the movie.

image from book
Figure 4-41: Displaying the last <contact> element in the document tree before and after the deletion

In the previous section, you saw some of the different ways that we can work with an XML document tree in Flash. We learned how to changes values, add new nodes, duplicate existing nodes with or without their child nodes, and delete nodes.

You can combine these methods to change your XML document tree within Flash. Bear in mind that although you carry out updates in Flash, you cant change the external document without using a server-side file. Well see this a little later in the chapter.

Well work through an example so you can see how we can update XML content within Flash using UI components in an application.

Putting it all together

Exercise 6: Adding a new image to the photo gallery XML tree
image from book

In this exercise, well load the external photoGallery.xml file into an XML object in Flash. Well then use a form to add a new image to the document tree. Well work through the following steps:

  1. Setting up the environment

  2. Validating the user changes

  3. Updating the document tree

The exercise wont update the external XML document. Well need a server-side file to do that, and well complete this step in the last exercise.

Setting up the environment

  1. Open the starter file galleryupdate.fla . Figure 4-42 shows the interface. Make sure that the photoGallery.xml file is in the same directory.

    image from book
    Figure 4-42: The galleryupdate.fla interface

The interface shows a ComboBox component, some text fields, an update button, and a dynamic text field that well use to display error messages. The user will select a gallery and fill in the details of the new photo.

  1. Test the Flash movie, and youll see that it loads the external XML file and populates the ComboBox component with photo gallery names.

Validating the form

We need to make sure that youve entered valid data before changing the structure of the XML document. You must have selected a gallery and entered a file name that ends in .jpg .

  1. Add the following event handler to the actions layer. The event handler will call an inline function when you click the Update button. The function checks to see that you have selected a gallery and entered a file name ending with .jpg . If you have entered the relevant details, the function clears the error message text field.

     update_btn.onRelease = function():Void {   selectedGallery = gallery_cb.selectedItem.label;   if (selectedGallery != "-- Select --" ){     if (filename_txt.text == "") {       error_txt.text = "Please enter a filename";     }     else if (filename_txt.text.indexOf(".jpg") == -1){       error_txt.text = "Please enter a filename ending in jpg";     }     else {       error_txt.text = "";   }   else {     error_txt.text = "Please select a gallery before clicking update";   } } 

Updating the XML document tree

After youve validated the data, you can find out the new values and use methods of the XML class to update the document tree.

  1. Change the inline function as shown here. Ive started by declaring some variables . The function finds the selected <location> node and creates a new <photo> node with the appropriate caption and filename attributes. It also adds a child text node containing the comment.

     update_btn.onRelease = function():Void {   selectedGallery = gallery_cb.selectedItem.label;  var currentGallery:String;   var comment:String;   var NewPhotoNode:XMLNode;   var NewPhotoCommentNode:XMLNode;  if (selectedGallery != "-- Select --" ){     if (filename_txt.text == "") {       error_txt.text = "Please enter a filename";     }     else if (filename_txt.text.indexOf(".jpg") == -1){       error_txt.text = "Please enter a filename ending in jpg";     }     else {       error_txt.text = "";  comment = comment_txt.text;   for (var i:Number=0; i < RootNode.childNodes.length; i++) {   currentGallery = RootNode.childNodes[i].attributes.   locationName;   if (selectedGallery == currentGallery){   GalleryNode = RootNode.childNodes[i];   NewPhotoNode = photoXML.createElement("photo");   NewPhotoCommentNode = photoXML.createTextNode(comment);   NewPhotoNode.attributes.caption = caption_txt.text;   NewPhotoNode.attributes.filename = filename_txt.text;   NewPhotoNode.appendChild(NewPhotoCommentNode);   GalleryNode.appendChild(NewPhotoNode);   trace (photoXML);   break;   }   }  }   }   else {     error_txt.text = "Please select a gallery before clicking update";   } } 
  2. Test the Flash movie. Enter values in the form and click the Update button. You should see an Output window displaying the new node. You can see an example in Figure 4-43. The completed file is saved as galleryupdate_completed.fla with your Chapter 4 resources.

    image from book
    Figure 4-43: Displaying the new <photo> node

Figure 4-44 shows the competed form used to create the new <photo> node.

image from book
Figure 4-44: The form providing input for the new <photo> node

Dont forget that the <photo> node is added to the document tree within Flash but not to the external XML file. Youll need to send the updated XML tree from Flash to a server-side file before you can update the photoGallery.xml file.

So far, weve looked at how you can create new XML content and change the existing document tree within Flash. If the content originally came from an external file, changes that you make inside Flash dont update that file. For security reasons, Flash doesnt have the ability to update external documents. Imagine how dangerous it would be if a Flash movie could work directly with the files on your computer.

To update an external XML document, youll need to send the document tree from Flash to a server-side file. The server-side file will then have to process the updates and save the changes to the external XML document. Well look at this in more detail in the next section of this chapter.

image from book
 


Foundation XML for Flash
Foundation XML for Flash
ISBN: 1590595432
EAN: 2147483647
Year: 2003
Pages: 93
Authors: Sas Jacobs

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net