Downloading XML

In the last chapter we built a highscore feature that loaded data from the server. This data was in a format called urlencoding (where variables are sent as name = value).

Now we upgrade this highscore feature to XML. We start with a simple XML formulation. Our data is in a file named highscore.xml and its entire contents is the line

 <?xml version="1.0" encoding="UTF-8"?><score>122</score> 

or just the business end


which is simply an element named score with a content of 122. It is useful to remember that 122 in this context is a string value, not a number. All XML content is text.

Opening the highscore MovieClip, we can update the first frame from

 loadVariables ("highscore.txt", this); 

to the XML equivalent

 highscore=new XML(); highscore.load("highscore.xml"); 

In the non-XML code, the load target is the MovieClip instance specified in the call ( this in our example) . In the new style, the target is an XML object. The MovieClip scope ( this ) is still significant. The XML object highscore that we just created is, in fact, this.highscore. Instead of creating a bunch of variables in this , we have created a single object, and our load will populate it.

The XML approach is, among other advantages, much safer. Consider the vulnerability when we invite a file to enter our namespace and establish variables there. These variables can inadvertently or maliciously overwrite important data.

The highscore.txt file in the first example might have included the statement


which would have lamed our highscore function. By contrast, nothing in XML coding could create such a name collision, intentionally or otherwise .

The XML.load method is much the same as the loadVariables function with which we are now familiar, except, of course, that its context is carried by the XML object on the left of the period rather than as a second argument to the function.

While loadVariables would load or send all the variables in its namespace, the XML.load method transfers only a single complex object with its own hermetic namespace.


It is important to point out a critical but subtle detail. In the previous chapter, we created functions in the highscore MovieClip. The functions used the keyword this to address the variables inside their instance of the highscore object. If there is a function myhighscore.func() and it addresses this.var , it refers to the variable myhighscore.var. By contrast, if there is also an object in the highscore MovieClip called myobj and it has a function that refers to this.var , the variable referred to is myhighscore.myobj.var. This might seem obvious, but it is very easy to overlook.

Flash and XML[c] A Developer[ap]s Guide
Flash and XML[c] A Developer[ap]s Guide
ISBN: 201729202
Year: 2005
Pages: 160 © 2008-2017.
If you may any questions please contact us: