Flash and XML

xiaoxiao2021-03-06  103

In the current age of technology, with all of the cool toys and gadgets that are available, all of these things exist for one purpose ... to allow us to more easily access information. Today, we are able to acquire information more quickly and easily than we has ever been possible in the past. Largely, this has to do with the internet and the fact that you can access information anywhere in the world from anywhere else in the world in literally the blink of an eye.

So we all know that the information is there, waiting for us to access it. The challenge we as developers face is how to get that information to the user. Up to this point, the information has largely been sitting in static HTML pages, just waiting to be read. The problem with this is that there is more work involved in changing or updating that information as the editor has to know HTML, CSS, etc. So recently, more and more information has moved from static pages to being stored in some "data repository". The most common is the relational database. The great thing about this is that the data is kept seperate from the layout, so you can change the data without having to deal with design issues. All you need is to have a server-side scripting environment (ie, ColdFusion, ASP, PHP, CGI, etc.) to extract the information from the database and display it for the user in HTML format. This is a wonderful system, however, since each relational database management System (RDBMS) IS ProPrietar y to a degree, it can require quite a bit of work for different databases to communicate with each other (plus you need to know the different server-side languages ​​to deal with all of this, along with SQL). Would not it be Nice if there is a standard warrings information That Was Platform and Language Independent?

Enter eXtensible Markup Language (XML). XML is a buzzword that has been thrown around a lot lately and for good reason. XML has been positioned as the STANDARDIZED way to transfer information that has been recommended by the W3C. This means that any application can potentially communicate with any other application as long as they communicate via this language. in a way, it's kind of like the Universal Translator they have in Star Trek. Each species speaks a different language, via but that language can be transmitted the translator in a way that each party can understand the others as long as the translator has the algorithms necessary to make sense of that language. This is the entire premise behind Web Services, which you will be hearing a lot about in the future.Essentially, XML is a Way to Describe Information in A Structured Way, That Is Human Readable. Thought i will go into a very brief explanation of xml, for more a few Excellent Resources Discuss ING XML:

»A Technical Introduction to XML» XML - Questions and Answers »An Introduction to the Extensible Markup Language

XML is strictly a language that DESCRIBES the information itself, unlike HTML which describes how the information should appear in a web browser. XML makes use of tags, just like HTML, however, the tags are used as descriptors of the data itself, instead of how the data should be laid out on a page. Thus, the person writing the XML is allowed to make up his / her own tag names and structure those tags in a way that gives context to the information contained within them. Here is a simple HTML ELEMENT Consisting of Tags:

phil chung

This code tells me that the browser should display "Phil Chung" as an individual paragraph, but tells me nothing about whether "Phil Chung" is the name of a Flash developer, a flesh-eating disease, or a clothing manufacturer. Take a look At The Following, However: Phil Chung

THIS XML IS A Little More Descriptive Than The HTML IN That Tells Me That "Phil Chung" is Somehow Related to "Flashdude". What if we take this a special further:

phil chung

The wonderful thing about this is that we can understand something about the information just by reading this XML. "Phil" is the first name of the first Flash dude in a list, and "Chung" is his last name. Notice that the syntax is very similar to HTML. However, XML is much more strict in the fact that every XML document must be WELL-FORMED (must comply to strict rules), or an error is thrown, unlike in HTML where a code mistake will not prevent the browser From displaying your page.

In Order for an XML DOC To BE Well-Formed, IT Must:

Use Properly Nested Elements. Contain Tags That Are Closed Properly (Either ""). Begin with a minimum of Contain Only 1 Root Element With All Elements Can Be Nested.

.

Ultimately, because XML is a standard language, information can be stored once in one format and viewed through a variety of different presentation formats (HTML, Flash, even PDF) .After gaining a basic knowledge of XML, we now turn to Flash to address The Question ... "AS A FLASH Developer, Why SHOULD I CARE ABOUT ANY OF THIS XML STUFF?"

Starting with Flash version 5 (and continuing with MX), Macromedia has seen the importance of XML in the grand scheme of things and has incorporated an XML parser into the Flash player. Essentially, a parser takes in information and converts it to a format that the native application can understand and deal with more easily. In Flash's case, the XML parser loads the external XML document (as one long text string), runs through all of the nodes (XML elements) and converts them into an object structure. Then Using ActionScript, We can Extract The Information We need and display it approprisely.

There Are Some Issues To Understand Before Working With XML in Flash:

The Flash XML Parser Is Not a Validating Parser (if You Don't Know What That Means, Don't Worry About It ... Skip to # 2). Therefore, Any Validation of XML Documents (if Necessary) SHOULD BE DONE BEFORE bringing the XML into Flash. For security reasons, Flash content on the web can only load data from an XML file in the same domain where the Flash file resides. However, you can load XML files from other domains by using a server-side script to redirect the URL of the XML file back to your Flash file. The XML parser in the Flash 5 player was painfully slow when dealing with large XML documents. This is because the parser was written in Actionscript. One way to overcome this was to use xmlNitro, a free script written by Branden Hall, which increased parsing speed significantly. fortunately, in MX, the parser is written in the native C code, and as a result is MUCH faster (see Flash 5 vs. MX XML parsing speed tests by Vaykent. The XML Parser in Earlier Versions of The Flash 5 Player Does not ignore whitespace in XML files. Whitespace consists of any characters between XML elements such as line breaks or tabs. This will affect your data once it's been parsed into Flash because every whitespace character may be seen as it's own node. In Flash 5, if You Wanted to Get Around this, You Have Basically 3 Options:

Tell the user to download the latest version of the Flash player (not always feasible). Remove all whitespace from your XML document (not good from a readability standpoint). Use a script that removes whitespace from the XML before Flash parses it. This is probably the best solution as it is very easy to incorporate an existing script into your Flash movie. There is an excellent stripWhite script written by Colin Moock that he has kindly made available for free.Fortunately, if you're working in Flash MX, you do not have to deal with the slow parsing issue or the whitespace issue (MX includes a property that can be set so that the parser ignores whitespace - see below). This tutorial is written for Flash MX, so it will not directly deal with The release.

Ok ... Now That Weame Got That Out of the Way, Let's Get Started Actually Looking At The XML in Flash.

In the remainder of this tutorial, we'll build a simple dynamic menu in Flash where the menu items (and associated information) will be drawn from an XML file (keep in mind that this is being done in Flash MX). Here is the Menu Below (Doesn't Look Too Fancy, But You'll See That All of The Menu Items Are Entirely Dynamic).

»Download Source

We willwrite the xml, loading the xml into flash, the deal with the pased information to create a menu.

To create the xml content, do the folowing:

Open a Text Editor Of Your Choice (Use notepad or textpad ... NOT A WORD Processing App Like Microsoft Word). Save the file as "mymenu.xml". Type in the folload: save the file again.

Notice that each menu item has it's own element. The information for each menu item is contained in ATTRIBUTES. The 2 attributes are "name" and "url" and each has a different value for each menu item. As you can see, we ' re trying to set this up in a way that the data is structured in a logical way. By no means is this the only way to do it. However, you should make note of how the data is organized because you will need that information when IT Comes Time To Extract and Display Time To Extract and Display THE INFORMATION IN FLASH. You Could Also Have Set IT Up Like this: Philter keran mckenzie StudiowHiz ... Sorenson

This time, we used only one attribute (url) and we placed the name as simple text inside of the myItem element. This provides essentially the same information as the first example, but does so in a slightly different way. As you can see, XML IS VERY FLEXIBLE IN A WAY THATOWS You to Store and Structure Your Information In A Way That Is Best Suited to the Type of Information You're Dealing with.

For this Example, We will be used the first XML Example I Gave. Thought this Menu is Very Simple, IT CAN Be Very Easily Expanded Up Buch. Submenu Items and Such.

Now ONTO The Flash Movie. In Your Flash Movie, Do The Following:

Create a filled rectangle on the stage (width: 150, height: 20). Convert that shape to a Movie Clip symbol Give it a name, set the registration to Top Left, and make sure "Export for Actionscript" is turned on and. set the "Identifier" name to "itemClip". Double click to edit the symbol. Create a new layer, and on that new layer insert a text field. Make sure it is set to "Dynamic" and set the instance name to "itemLabel ". Also, make sure that" Selectable "is turned off. Be sure to make your font color of appropriate contrast to your rectangle fill color. Return to the root timeline. Delete the symbol you just created from the stage. (We are going to attach this movie clip dynamically to the stage using Actionscript) Create a new layer This layer will contain all of the script needed for this tutorial Open the Actions panel and type in (or copy and paste) the following:... menuXml = new XML (); menuxml.ignorewhite = true; menuxml.onload = function (success) {if (success) {menuitem = t His.FirstChild.childNodes; for (var i = 0; i

Now Let's Go Through the code line by line to see exactly what is happensing (again, remember what this code is written in).

This line creates a new instance of the XML object and attaches the name "menuXml" to it. After this, if you want to refer to your XML object, you can just refer to the instance name you set. You HAVE to do this if You Want to Work with XML in Flash.

Menuxml.ignorewhite = true;

Next, we use the "ignoreWhite" property of the XML object and give it a value of true. This tells Flash to ignore the whitespace in your XML document (see discussion on white space above). This property is only available in Flash player 5r41 OR HIGHER.

Menuxml.Load ("MyMenu.xml");

Skipping right down to the bottom for now, we use the "load" method of the XML object which accepts one parameter - the path to the XML file you want to load Since the XML file is located in the same directory as our fla /. SWF file, We Just Have to Tell It The FileName.

Now We come to the bulk of the code ... The part That Actually Does stuff with the xml information overce it Has Been loaded and paarsed in flash. Again, Let's Break it Down Line by Line:

Menuxml.onLoad = function (success) {

The XML Object Has 2 Event Handlers Associated with It: OnData and Online.

"OnData" executes when the XML data has finished loading, but has not been parsed yet. Sometimes you may want to use the raw XML data before it has been parsed (particularly in Flash 5, where the parsing was slow), however, in most cases, you would use the "onLoad" handler. "onLoad" executes when the XML data has finished loading and has been parsed by Flash's XML parser. This is the event we will need to capture.The "onLoad" handler is an empty function. Basically, that means that when the "onLoad" event occurs, by default, nothing will happen, unless you tell it to do something. The way you tell it to "do something" is by assigning a callback handler to it. The .

If you are all, you can Just Assign IT AS IN THE EXAMPLE ABOVE (Using An Unnamed Function).

Menuxml.onLoad = function (success) {stuff goes here;}

If you want to reuse the function, you will want to create a named function and assign that function to the handler. Notice here that when assigning the callback handler, we write "myCallback" instead of "myCallback ()" because we are not executing The function with this line of code, we are just assigning the function to the "onload" handler.

Function mycallback (success) {stuff goes here;} menuxml.onload = mycallback;

Now, back to our example. You may have noticed that the callback function contained a parameter called "success". This is a parameter that is set to either "true" or "false" depending on whether the XML was loaded and parsed successfully. This is handy because now we can test the value of the "success" parameter and either do what you want with the information (if it is available), or tell the user that the XML did not load successfully. We do that in our next Line: IF (Success) {

. This line says to only execute the following code if "success" To put it another way, this is exactly the same as saying "if (success == true);". But we save ourselves a little typing Next, we begin to EXTRACT THE Information ...

Menuitem = this.firstchild.childNodes;

First, I need to find my way through the XML object structure that the Flash player has so kindly parsed my data into. If you look back at the XML structure we created, you see that we have as our root element "" , and that element contains 4 "child" elements called "". Any element that is nested inside another element is considered a "child of that" parent "element. The nested elements also have a" sibling "relationship to each other ............................

So the important elements (which I will refer to as nodes from here on in) are the "" nodes. These nodes contain the actual information I need to build my menu. To access these nodes, I say "this.firstChild .childnodes ". There Are 3 parts to the path statid Here:

"This" refers to the XML object instance "menuXml". That is because this code is located in the function assigned to the "menuXml.onLoad" handler. "FirstChild" is a property that refers to the first child node of the root node In this example. in this case it is "". "ChildNodes" Returns An Array That Contains All of the child Node Case, The Array Will Contain All of the four "" Nodes.we Take this Information and Store IT IN The Variable "MenuItem" SO We can Reference It Later On Without Having to Type "this.firstchild.childNodes" over and over again.

For (VAR i = 0; i

IN ORDER TO Extract All of the Information We need to be aable to loop through and extract information from each of the "" Nodes (IE, The "name" and "url" data ). You can do this Several Ways, But IN Our Example, We'll Use a "for" loop. This Type of loop consists of 3 parts:

Initialization (var i = 0) - this set the initial value of the "ity". Condition (i " nodes in the XML object) Increment / Decrement (i ) -. This tells the iteration variable to increase by 1 every time through the loop.

So this loop will allow us to extract information beginning with the first element in the array (remember arrays begin at index 0) to the last element in the array.item = _root.attachMovie ( "itemClip", "itemClip" i, i );

With each node (array item), we first dynamically attach the movie clip we created to the stage using the "attachMovie" method and store it in a variable called "item". Again, this allows us to reference the attached movie clip without having To write the path to this clip every time. The "attachmovie" Method Takes 3 parameters:

Identifier name ( "itemClip") - This is the name we set in the "Identifier" field when we set the movie clip to "Export for Actionscript" Instance name ( "itemClip" i) -. This is the instance name of the Movie Clip We've Attached. Depth (i) - this sets the defth (z-index) of the attachde.

So, for every "" Node in the XML File, A New Movieclip is attached to the stage.

Item._x = 0;

THIS STS The "_X" Property (Position of the Clip on The Stage In x Direction) To 0, Which is The Very Left Edge of The Stage.

Item._y = 20 * i;

THIS SETS THE "_Y" Property (Position of the Clip on The Stage in Y Direction) To a Different Value Depending On What The Value Of "I" is. By Multiply "i" by 20, The Menu Items Will Cascade Vertical, And Will Be Offset 20 Pixels from The Previous Item.

Item.itemlabel.text = menuitem [i] .attributes.name;

Next, We want to extract the "name" attribute from the "" Node to Display It in Our Dynamic Text Field. We can do what "MenuItem [i]" to Find The Current Node (Array Item). So in our example, menuItem [0] would represent the first "" node. We then use the attributes property, and the "name" attribute specifically to extract that information.After extracting the information, we have to display it in the text field somehow. in Flash MX, text fields are treated as objects and can now have instance names (whereas in Flash 5 you had to use a variable name). to insert text into the text field, we will use the "text" Property of The Text Field ("ItemLabel" Was The Instance Name). And Since The Text Field Is Inside of The Movie Clip, We Use The Path "Item.Item.Text".

item.myurl = menuItem [i] .attributes.URL;

The other piece of information we need is contained in the "url" attribute. We can access this the exact same way as the "name" attribute, just replacing "url" for "name". Then, we are just going to store this For now in a variable i number "Myurl" Which is located in the movie clip.

The last thing that needs to be done is to create the action so that when the user presses one of the menu items, a new browser window will open with the url we've set. However, notice that we have not created a button symbol yet (and we will nOT be creating one at all!). In Flash MX, movie clips are equipped with pretty much all of the same event handlers as buttons have. not only that, but the event handlers do not have to be attached to The Specific Movie Clip (OR Button) in Flash MX. You can Dynamically Set An Event Handler In Much The Same Way AS We Did with "Online" Earlier ... by using a callback handler.Item.onRelease = function () {

Here, we'll use the "onRelease" handler of the "item" movie clip that we just attached. We assign this to an unnamed function. This is great because by placing this code here, we no longer have to hunt around in our Flash Movie to Find The Appropriate Button or Movie Clip. We Just Have To Look in Frame 1 of the root time!

GetURL (this.myurl, "_ blank");

The Final Thing We Have to Do Is Tell Flash What To Do When The "Onrelease" Event Occurs. This is a Simple "geturl" Command Tells Flash to open the url "this.myurl". This is just calling on the variable " MyURL "That We create from the" URL "Attribute of Our XML file.

THEN, AFTER WE End The Appropriate Functions, For Loops, And If Statements Using "{", We're Done. This Menu IS generated Dynamically Via The XML Data. Don't Believe Me? Export The Swf File, Then Go Back to Your xml file and add or remove one of the "" nodes. Then, Reopen Your swf file and see what happens :)

Obviously, this is a very simple example. However, You Can Expand this Concept to create Very ElaBorate XML Driven Flash Front-Ends. Here Are A Couple of Examples:

»Macromedia XML Feed Reader

This is a Flash interface that extracts information from a publicly accessible news feed created by Macromedia and allows you to sort it by several different categories, all of which are described in the XML document.

»RSS News Reader

A Flash interface that reads news feeds in RSS format (an XML implementation). This brings in news feeds that have been syndicated from various sources (mostly blogs) and provides a Flash front end to these news items.

Downloads & more

»Download Source

»Download all in zip

转载请注明原文地址:https://www.9cbs.com/read-123621.html

New Post(0)