Creating XML Content within Flash

You can use Flash to create XML content, without the need to load it first from an external file. You may want to do this to send an XML fragment to an external application. Ive used this process to request information from external systems. The request required an XML document, so I created the content within Flash and used the sendAndLoad method to send the XML packet to the application. Youll learn more about sending information from Flash later in this chapter.

There are two ways to create XML content from Flash. Either you can create an XML string and add it to your XML object, or you can use methods such as createElement and createTextNode to generate the structure programmatically. Well start by looking at the first approach.

Creating an XML string

The easiest way to create a simple XML fragment is by creating an XML string, as shown here. When you do this, Flash wont determine whether the XML is well formed or valid.

 var myXML:XML = new XML("<name>Sas</name>"); 

In the example, the XML object contains a single XML node, <name> . Where the string is longer, it can be useful to add it to a variable, as shown here:

 var XMLString:String; XMLString = "<login><name>Sas</name><pass>1234</pass></login>"; var myXML:XML = new XML(XMLString); 

You can also use the parseXML method to add content to an existing XML object:

 var XMLString:String; XMLString = "<login><name>Sas</name><pass>1234</pass></login>"; var myXML:XML = new XML(); myXML.parseXML(XMLString); 

The parseXML method replaces any existing content within the XML tree, which means it isnt a good candidate where you need to preserve the current tree. My preference is for the first approach so that I dont overwrite any XML content by mistake, but either method will achieve the same result.

Whichever method you choose, it might be better to set out the XML string so that you can read it more easily. In this example, its easier to read the nodes within the XML fragment compared with the earlier example:

 XMLString =  "<login>"; XMLString += "<name>Sas</name>"; XMLString += "<pass>1234</pass>"; XMLString += "</login>"; 

The file createXMLstring.fla contains the example shown here. The XMLString variable stores the XML content in string format. The code adds the variable to the myXML object and displays it in the Output window.

 var XMLString:String; XMLString =  "<login>"; XMLString += "<name>Sas</name>"; XMLString += "<pass>1234</pass>"; XMLString += "<browser>IE</browser>"; XMLString += "<os>PC</os>"; XMLString += "</login>"; var myXML:XML = new XML(XMLString); trace(myXML); 

Figure 4-26 shows the movie when tested .

image from book
Figure 4-26: Displaying the contents of the XML object

Once youve created the XML object, you can extract the content using the properties discussed earlier. For example, the line that follows creates the output shown in Figure 4-27.

 trace(myXML.firstChild.firstChild.firstChild.nodeValue); 
image from book
Figure 4-27: Displaying the contents from an XML object created in Flash

You need to be careful if your XML string includes attributes. Well-formed XML documents use quotation marks around attribute values, and these will cause problems in your code unless you escape them with the backslash character ( \ ).

Heres an example. Ive escaped the quotes around the attribute value "first" with backslashes so it reads \"first\" . You can find this example in the resource file createXMLString.fla .

 var XMLQuotesString:String; XMLString =  "<login>"; XMLString += "<name type=  \"first\"  >Sas</name>"; XMLString += "<pass>1234</pass>"; XMLString += "</login>" var myQuotedXML:XML = new XML(XMLString); trace(myQuotedXML); 

You can see that its easy to create content using strings of XML information. An alternative method is to create XML content with ActionScript, using methods of the XML class.

Creating XML using methods

The methods of the XML class that you can use to create XML content include

  • createElement

  • createTextNode

  • appendChild

  • insertBefore

  • cloneNode

  • removeNode

Well look at the cloneNode and removeNode methods later in the chapter when we look at modifying existing XML content.

Creating new elements

You add a new element by creating it and either appending or inserting it into your document tree. This example shows how you can create an element:

 var myXML:XML = new XML(); var RootNode:XMLNode = myXML.createElement("login"); 

When you use the createElement method, it doesnt have a position in the document tree. You will have to use either the appendChild or insertBefore method to place it in the tree.

The appendChild method adds the node at the end of the current childNodes collection. The next example uses this method to add a new child to the XML object. In fact, as its the first child of the XML object, were adding the root node of the XML document.

 myXML.appendChild(RootNode); 

If you want to use the insertBefore method, the parent node will have to have at least one existing child node within the document tree. This example shows how to use insertBefore :

 var BrowserNode:XMLNode = myXML.createElement("browser"); var OSNode:XMLNode = myXML.createElement("os"); RootNode.appendChild(OSNode); RootNode.insertBefore(BrowserNode, OSNode); 

In our earlier XML string example, we worked with the following XML structure:

 <login>   <name>Sas</name>   <pass>1234</pass>   <browser>IE</browser>   <os>PC</os> </login> 

The next example uses the appendChild method to create the same XML structure. At the end, it traces the document tree in an Output window. You can see the example in the resource file createXMLMethods.fla .

 var myXML:XML = new XML(); var RootNode:XMLNode = myXML.createElement("login"); var NameNode:XMLNode = myXML.createElement("name"); var PassNode:XMLNode = myXML.createElement("pass"); var BrowserNode:XMLNode = myXML.createElement("browser"); var OSNode:XMLNode = myXML.createElement("os"); myXML.appendChild(RootNode); RootNode.appendChild(NameNode); RootNode.appendChild(PassNode); RootNode.appendChild(BrowserNode); RootNode.appendChild(OSNode); trace (myXML); 

Figure 4-28 shows how the movie appears when tested. Note that the child elements are empty because we havent yet added any text elements.

image from book
Figure 4-28: Displaying the XML document tree

I could have achieved the same result by using the insertBefore method. Ive shown this in the example that follows, and it is also available in the createXMLMethods.fla resource file. Youll have to uncomment the relevant lines within the file if you want to test the code.

 var myXML:XML = new XML(); var RootNode:XMLNode = myXML.createElement("login"); var NameNode:XMLNode = myXML.createElement("name"); var PassNode:XMLNode = myXML.createElement("pass"); var BrowserNode:XMLNode = myXML.createElement("browser"); var OSNode:XMLNode = myXML.createElement("os"); myXML.appendChild(RootNode); RootNode.appendChild(OSNode); RootNode.insertBefore(BrowserNode, OSNode); RootNode.insertBefore(PassNode, BrowserNode); RootNode.insertBefore(NameNode, PassNode); trace (myXML); 

If you traced the document tree code, it would appear identical to the output in Figure 4-28. The two methods achieve the same result, but there is one difference. Using insertBefore , I have to start with the last child node in the tree and work my way up through the child nodes. If I use appendChild , I start at the beginning and work my way down to the last child node. You can compare both examples in the resource file createXMLMethods.fla .

To complete the document tree, we need to add text to the child nodes. Text nodes are child nodes of the parent element node. In this line, for example, Child text is a child node of the <pElement> node:

 <pElement>Child text</pElement> 

In Flash, Id refer to it using one of these two lines:

 pElementNodeRef.firstChild; pElementNodeRef.childNodes[0]; 

Creating new text nodes

You use the createTextNode method to add text to an element:

 var myXML:XML = new XML(); var TextNode:XMLNode = myXML.createTextNode("Some text"); 

As with element nodes, when you first create a text node it has no position in the document tree. You will need to use the appendChild method to add this node into the XML object. In Flash, a text node is always a child of an element node. You can see this in the following example:

 var myXML:XML = new XML(); var RootNode:XMLNode = myXML.createElement("login"); var ChildNode:XMLNode = myXML.createElement("name"); var NameTextNode:XMLNode = myXML.createTextNode("Sas"); myXML.appendChild(RootNode); RootNode.appendChild(ChildNode); ChildNode.appendChild(NameTextNode); 

In the example, weve created a root node and child node and appended them to the document tree. The createTextNode method creates a text node containing Sas and appends it as a child of ChildNode . Figure 4-29 shows how myXML would appear if shown in the Output window.

image from book
Figure 4-29: Displaying the XML document tree, including a text node

Earlier we created the structure for the login XML document. We generated the elements and the code here illustrates how you could add the text nodes. In this example, Ive used the appendChild method for all nodes. Ive shown the new lines in bold.

 var myXML:XML = new XML(); var RootNode:XMLNode = myXML.createElement("login"); var NameNode:XMLNode = myXML.createElement("name"); var PassNode:XMLNode = myXML.createElement("pass"); var BrowserNode:XMLNode = myXML.createElement("browser"); var OSNode:XMLNode = myXML.createElement("os");  var NameTextNode:XMLNode = myXML.createTextNode("Sas Jacobs");   var PassTextNode:XMLNode = myXML.createTextNode("1234");   var BrowserTextNode:XMLNode = myXML.createTextNode("IE");   var OSTextNode:XMLNode = myXML.createTextNode("PC");  myXML.appendChild(RootNode); RootNode.appendChild(NameNode); RootNode.appendChild(PassNode); RootNode.appendChild(BrowserNode); RootNode.appendChild(OSNode);  NameNode.appendChild(NameTextNode);   PassNode.appendChild(PassTextNode);   BrowserNode.appendChild(BrowserTextNode);   OSNode.appendChild(OSTextNode);  trace (myXML); 

You can find the example in the resource file createXMLMethodsText.fla . Figure 4-30 shows how this example appears when tested.

image from book
Figure 4-30: The completed example

If you compare the number of lines of code that it took to create this output with the example that used an XML string, youll see that its a much longer way of creating a new document tree. Given that it takes more work, why would you use XML methods to create a new document? Well, you can use the methods shown in this section to work with an existing document tree, so its worthwhile getting a good understanding of how they work.

In the next section, Ill look at how you can add attributes to the document tree using ActionScript.

Creating attributes

Adding attributes to elements within Flash is very easy. You just set the name and value of the attribute as shown here:

 var myXML:XML = new XML(); var RootNode:XMLNode = myXML.createElement("login"); var ChildNode:XMLNode = myXML.createElement("name"); myXML.appendChild(RootNode); RootNode.appendChild(ChildNode);  ChildNode.attributes.type="first";  

I could also have written the last line using associative array notation:

 ChildNode.attributes["type"]="first"; 

You can see this example in the resource file createXMLMethodsAttributes.fla . Figure 4-31 shows the Output window that displays when testing the movie.

image from book
Figure 4-31: The Output window showing an attribute

In the examples weve worked with so far in this section, we havent included an XML declaration in the document tree. Youll recall that this declaration is optional, but some external applications may require that you include it when you send XML content out of Flash. The next section shows you how to add this declaration to your XML packet.

Adding an XML declaration

The xmlDecl property allows you to set or read the XML declaration within the XML document tree. It doesnt matter whether youve created the document using an XML string or using XML methods. When you first create the document within Flash, the value of the xmlDecl property is set to undefined .

You can add an XML declaration by setting the property as shown here. Notice that Ive escaped the quotation marks with a backslash character. If I dont do this, Ill get an error message in Flash.

 var myXML:XML = new XML(); myXML.xmlDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; 

I dont need to place the declaration in the document tree as Flash will automatically add it in the appropriate place once Ive set the value. You can see an example of this in the resource file createXMLExtras.fla . Its also shown in Figure 4-32 in the next section.

image from book
Figure 4-32: The document tree including XML and DTD declarations

Adding a DOCTYPE declaration

Flash includes the docTypeDecl property so that you can read and set a reference to a DTD. A DTD allows you to validate your XML document, but Flash wont try to perform any validation when it detects a reference to this type of file. Flash cant validate XML documents as it contains a nonvalidating parser.

You can set a reference to a DTD by using the following code. As with the XML declaration, I had to escape the quotes in the declaration.

 var myXML:XML = new XML(); myXML.docTypeDecl = "<!DOCTYPE documentRoot SYSTEM \"file.dtd\">"; 

Again, Flash automatically places this declaration at the correct position in the document tree. You can see an example in the resource file createXMLExtras.fla . Figure 4-32 shows the content of the document tree from the example file.

Youve seen two different approaches to generating XML content within Flash: using an XML string and using XML class methods. While the XML string approach is quicker, it will replace any existing content within an XML object. If youre manipulating an existing XML tree, you will have to rely on the methods of the XML class. There are some limits to these XML class methods.

Limits of XML methods

You may have noticed that we havent used Flash methods to add XML processing instructions. Thats because this is not possible in Flash. Unfortunately, it might be required if you need to create an XML document for an external application that includes a reference to a style sheet. To achieve this, youll have to create the XML document using an XML string. Similarly, if you need to include namespaces or schema references in the XML document, youll also have to use an XML string to create the document tree.

The next example shows how you can include these elements in your document tree. Youll need to escape the quotes in the style sheet declaration and in the schema declarations within the <login> element. You can see the example in the resource file createXMLOther.fla .

 var XMLString:String; XMLString = "<?xml-stylesheet type=\"text/xsl\" href=\"style.xsl\"?>"; XMLString +="<login "; XMLString +="xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""; XMLString +="xsi:noNamespaceSchemaLocation=\"schema.xsd\">"; XMLString +="<login>"; XMLString +="<name>Sas</name>"; XMLString +="<pass>1234</pass>"; XMLString +="<browser>IE</browser>"; XMLString +="<os>PC</os>"; XMLString +="</login>"; var myXML:XML = new XML(XMLString); 

Figure 4-33 shows the output when you trace the contents of myXML .

image from book
Figure 4-33: The document tree including style sheet and schema declarations

Putting it all together

In the preceding section, you learned how to create XML tree structures in two different ways. We used an XML string to add content to the document tree. We also used XML class methods to add elements programmatically.

In the example that follows, well use a combination of both approaches to create an XML document within Flash.

Exercise 5: Creating the address.xml file structure within Flash
image from book

In this example, well use Flash to create the XML document tree shown here. It is a cut-down version of the address.xml file that youve seen previously. Well start by adding the XML declaration and root node using an XML string. Well add the contacts using methods of the XML class.

 <?xml version="1.0" encoding="UTF-8"?> <phoneBook>   <contact id="1">     <name>Sas Jacobs</name>     <address>Some Country</address>     <phone>123 456</phone>   </contact>   <contact id="2">     <name>John Smith</name>     <address>Another Country</address>     <phone>456 789</phone>   </contact> </phoneBook> 
  1. Create a new Flash document called createAddressXML.fla .

  2. Name the first layer actions and add the following code to frame 1. The code creates an XML string and an XML declaration for the XML object myXML .

     var XMLString:String = "<phoneBook/>"; var myXML:XML = new XML(XMLString); myXML.xmlDecl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; trace (myXML); 
  3. Test the movie. You should see an Output window similar to the example shown in Figure 4-34. The window displays an XML declaration and an empty root node.

    image from book
    Figure 4-34: Displaying the XML declaration and root node

  1. Add the following arrays to the actions layer. The arrays contain the content for the XML document. Storing the information in arrays allows us to add content to the XML tree within a loop.

     var arrNames:Array = new Array("Sas Jacobs","John Smith"); var arrAddress:Array = new Array("Some Country", "Another Country"); var arrPhone:Array = new Array("123 456", "456 789"); 
  2. Create the <contact> nodes as shown here. Ive added the id attribute to the node and set it to be one more than the value of i . In other words, the id will start at 1 . I also created the variables that Ill need a little later.

     var ContactNode:XMLNode; var NameNode:XMLNode; var AddressNode:XMLNode; var PhoneNode:XMLNode; var TextNode:XMLNode;   for (var i:Number=0; i < arrNames.length; i++) {   ContactNode = myXML.createElement("contact");   ContactNode.attributes.id = i + 1;   myXML.firstChild.appendChild(ContactNode); } 
  3. Test the movie. You should see something similar to the screenshot displayed in Figure 4-35.

    image from book
    Figure 4-35: Displaying the contact nodes and attributes

  4. Modify the for loop as shown in the bold lines in the following code. Weve created the child elements and text elements and appended them to the <contact> nodes. Ive added spaces to make the blocks easier to understand.

     for (var i:Number=0; i < arrNames.length; i++) {   ContactNode = myXML.createElement("contact");   ContactNode.attributes.id = i + 1;   myXML.firstChild.appendChild(ContactNode)  NameNode = myXML.createElement("name");   AddressNode = myXML.createElement("address");   PhoneNode = myXML.createElement("phone");   TextNode = myXML.createTextNode(arrNames[i]);   NameNode.appendChild(TextNode);   ContactNode.appendChild(NameNode);   TextNode = myXML.createTextNode(arrAddress[i]);   AddressNode.appendChild(TextNode);   ContactNode.appendChild(AddressNode);   TextNode = myXML.createTextNode(arrPhone[i]);   PhoneNode.appendChild(TextNode);   ContactNode.appendChild(PhoneNode);  } 
  5. Test the movie. You should see something similar to the example shown in Figure 4-36. Weve used Flash to create the XML document shown earlier. You can see the completed example in the resource file createAddressXML.fla .

    image from book
    Figure 4-36: Displaying the finished XML file

In addition to creating XML document trees within Flash, its important to be able to manipulate existing trees and modify the content that they contain. You might need to do this if youre allowing a user to change the values in your Flash XML application. You need to apply the changes to the document tree, so well look at that in the next section.

image from book
 


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

Similar book on Amazon

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