Tài liệu Using the XML Class doc

17 297 0
Tài liệu Using the XML Class doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

< Day Day Up > Using the XML Class It's time to start using some XML! Nearly everything you do with XML in Flash involves the XML class and falls into one of the following categories: formatting XML, parsing XML (extracting the information), loading XML, or sending XML. With the XML class, you can load XML from an external source such as a static file or a server-side script. After an XML document is loaded, you can access its information using the methods and properties of the XML class. You can also use the methods and properties of the XML class to create your own XML document. After this document is created, you can use it in a Flash movie or send it out to a server-side script. This section covers the ActionScript you need to accomplish these goals. Formatting XML The XML class in Flash has several methods, most of which you can use to create and format XML documents. The truth is, though, you're unlikely to employ them because they're difficult to use—and there's a better way. We'll show you how to create a string and then convert it into an XML object, a much easier (and more common) way of formatting XML objects. To create an XML object in Flash, you must use the XML class constructor. Here's how you would create an empty XML object: var myXML:XML = new XML(); To populate the object with XML-formatted data when it's created, you can pass (inside the parentheses of the constructor) the name of a variable that holds an XML-formatted string or another XML object. Suppose you want to create the following XML document in Flash: <MyFriends> <Name Gender="female">Kelly Makar</Name> <Name Gender="male">Free Makar</Name> </MyFriends> You would do two things: 1. Create the document as a string. 2. Convert the string to an XML object by using the XML class constructor new XML(). Here's an example: var myString:String = "<MyFriends> <Name Gender=\"female\">Kelly Makar</Name> <Name Gender=\"male\">Free Makar</Name></MyFriends>"; var myXML:XML = new XML(myString); This code creates the XML document as a string and converts it to an XML object called myXML. This object can then be sent to the server using the send-related methods described later in this section of the lesson. Parsing XML The word parse simply means to analyze something or break it down into its parts. When someone speaks of writing a script to parse an XML document, they're talking about writing a script that extracts information from that XML document. The XML class has many properties to help you do this. We'll use the XML object just discussed, myXML, to illustrate the use of a few of the most common properties. firstChild: This property points to the first node in the tree structure. For example: myXML.firstChild.firstChild returns <Name Gender="female">Kelly Makar</Name> The first child node of the XML document is the root node (MyFriends), and the root node's first child is Name, as shown. childNodes: This property returns an array of the child nodes at any given point in the tree structure. For example: var myArray:Array = myXML.firstChild.childNodes Here, myArray contains two elements whose values are the same as those of the two Name nodes. nextSibling: This property points to the next node in the same level of the tree structure. Thus, myXML.firstChild.firstChild.nextSibling returns: <Name Gender="male">Free Makar</Name> attributes: This property returns an associative array of attribute names. For example: myXML.firstChild.firstChild.nextSibling.attributes.Gender returns: "male" These examples represent the most commonly used properties of the XML object; others work in the same way, referencing different parts of the tree structure. Loading XML Typically, you'll only work with XML in Flash when you're loading or sending out the XML. To load XML from a remote source, do the following: 1. Create an XML object. 2. Use the load() method of the XML object to load XML-formatted data from an external source. For example: 3. 4. var myXML:XML = new XML(); 5. 6. myXML.load("http://somedomain.com/info.xml"); 7. Although in this example the document being loaded is a static XML file, it doesn't have to be. You can also point to an ASP page (or another scripted page) whose result is an XML document. To determine when the XML has finished loading into an object, you use the onLoad event available to the XML object. You can define this event to call a function when the document is finished loading. Consider the following example: function init () { //parse script here } var myXML:XML = new XML(); myXML.onLoad = init; myXML.load("http://somedomain.com/info.xml"); As the next-to-last line shows, when the XML document is finished loading, the init() function will be called. In the init() function, you write special code to interpret the XML. For example, if you're expecting an XML-formatted address book, you write some special code to walk the XML nodes, pulling out the data within them. We'll show some simple parsing examples later in this lesson. Sending XML The XML class allows you to send XML to a URL. It also enables you to send XML and load the resulting document simultaneously. To send XML to a URL, use the send() method and specify a destination URL: var myXML:XML = new XML("<Message><Text>Hi!</Text></Message>"); myXML.send("http://somedomain.com/somedestination.asp"); To send XML and receive a response, all in one shot, use the sendAndLoad() method of the XML object. With this method, you must specify an XML object whose contents you want to send, a URL in which to send the XML document, and an XML object in which to receive the response. As with the load() example described earlier, you must define an onLoad event to handle the loaded XML. Here's an example: var URL:String = "http://www.myDomain.com/UserLogin.asp"; function init () { trace(objToReceive); } var xmlToSend:String = "<Login><Username>Jobem</Username><Password>hayes</Password></Login>"; var objToSend:XML = new XML(xmlToSend); var objToReceive:XML = new XML(); objToReceive.onLoad = init; objToSend.sendAndLoad(URL, objToReceive); This ActionScript creates an XML object (objToSend) containing login information and then sends that information to a URL, where it waits for a response from the destination. When the response is fully loaded into the receiving XML object (objToReceive), the init function is called. Now that you know a little bit about the XML format and the XML class, it's time to put that knowledge to use. In the following exercise, you'll format a few simple XML documents, perform some easy parsing, and use sendAndLoad() to create a simple Flash application that acts as a registration/login screen. The Flash file used in this section communicates with ASP pages. To fully build and test this file, you'll need access to a server where you can run ASP scripts (this usually means a Windows server). To test the files in this exercise, you'll need to upload two ASP files (AddUser.asp and UserLogin.asp) and one Microsoft Access database file (XMLExample.mdb) to the same directory on a Windows server. These files can be found in the Lesson12/Assets folder. NOTE The ASP pages used in this lesson read and write to the database file. On most Windows servers, the permissions settings allow this exchange to take place. If you're having trouble getting the ASP files to perform correctly, ask your administrator or ISP to change the permissions settings to allow your ASP pages to access the database. We understand that not everyone reading this book has access to a Windows server. Because there are so many different server languages, it would be impossible to create supporting files for all of them. We chose ASP because of its ease of use and universality. Lack of a Windows server shouldn't diminish the value of the instructions that follow, however, because everything is explained in detail anyway. The AddUser.asp page accepts an XML document structured as follows: <Register> <Username>jobem</Username> <Email>jobe@electrotank.com</Email> <Password>secret</Password> </Register> If the user was registered properly, this page (AddUser.asp) returns the following result: <Register> <Message>User Inserted</Message> </Register> If a user of the same name already exists, the ASP page returns this result instead: <Register> <Message>User Exists</Message> </Register> The UserLogin.asp page accepts an XML document structured as follows: <Login> <Username>jobem</Username> <Password>secretword</Password> </Login> If the information provided was correct, this page returns the following result: <Login> <Message>Login Correct</Message> </Login> If the information provided was incorrect, the page returns this result instead: <Login> <Message>Login Incorrect</Message> </Login> 1. Open loginRegister1.fla in the Lesson12/Assets directory. This file already includes all the frames, text fields, and buttons needed for this example. The file contains four layers: The Actions layer is where we'll write all the ActionScript; the Labels layer contains the frame labels we need; the Assets layer contains text fields (in the form of TextInput component instances) and buttons; and the Background layer contains the interface graphics. 2. With the Actions panel open, select Frame 1 of the Actions layer and add a stop() action. By placing a stop() action here, we prevent the movie from playing automatically. 3. Add the following script to the frame: 4. 5. login_btn.onRelease = function() { 6. 7. _root.gotoAndStop("Login"); 8. 9. }; 10. There is a button on the Assets layer on Frame 1 that has an instance name of login_btn. The script in this step assigns a function to the onRelease event handler for that button. The user clicks this button to go to the login frame, where he or she can log in. [...]... document and extract the information When the user clicks the Submit button, the contents of the three text fields are used to format an XML document That XML document is then sent to the AddUser.asp page to be parsed, and the relevant content is added to the database The ASP page returns a response, which is captured by the function added in Step 10 10 Add the following function definition after the. .. } 22 23 } 24 The function in this step is called as soon as the last byte of XML is loaded into the XML object called objToReceive, as described in Step 6 The function in Step 7 parses the XML response from the server The loginResponse() function creates a variable named response and sets its value based on the data extracted from the returned XML document Remember that the response of the UserLogin.asp... with XML objects—we can't apply it to a string Next, we create a new object named objToReceive This is the XML object into which the ASP page's response is loaded Using the onLoad event, we tell the objToReceive object to call the loginResponse() function after the XML data has been loaded into it We'll create the loginResponse() function in the next step The next action in the function invokes the. .. of submit_btn The function begins by using the values entered in the username_ti and password_ti TextInput component instances to format the XML that we're sending to the ASP page, and then places that formatted data into a string variable named xmlToSend Next, we create a new XML object named objToSend and pass it the XMLformatted string we just created The reason for doing this is that the sendAndLoad()... instance called submit_btn on the stage With the Actions panel open, select the frame on the Actions layer at that label and add the following line of script: 6 7 var loginURL:String = "http://www.yourdomain.com/UserLogin.asp"; 8 The variable loginURL points to the ASP page that accepts the login XML document (located at the domain where you uploaded it) The ASP page parses the document that you send and... 29 30 }; 31 The ActionScript in this step is similar to that used in the Login frame label defined in Step 6 the only differences are in the format of the XML and some reference names Notice that the XML document here contains three pieces of user information: username_ti.text, email_ti.text, and password_ti.text This is the information entered into the TextInput instances by the user The destination... outside the function definition, but objToSend (used to hold and then send outgoing XML) is created within the function definition The reason is that any variables or objects created within the function itself (using the var keyword) are considered local to the function, and thus are deleted from memory as soon as the function has finished executing, which takes only a split second While the sending of XML. .. of submit_btn on the stage With the Actions panel open, select the frame on the Actions layer at that label and add the following line of script: 9 10 var registrationURL:String = "http://www.yourDomain.com/AddUser.asp"; 11 This is the ASP page that accepts the registration XML- formatted document It will process the information and return a result Be sure to enter the correct path to the file that you... accomplished within the timeframe of the function's execution, it may take several seconds for the resulting XML to load into objToReceive, which is why that object must exist after the function has finished executing If it was deleted when the function was finished executing, there would be no object into which to load the resulting XML 7 Add the following function definition after the one you added... specifying the object to send, the destination URL, and the object in which to load the response Finally, the last action sends the timeline to a frame named Waiting This frame informs the user that the information was sent but no response has been returned The movie stops on this frame until it receives a response from the server You may wonder why objToReceive (which is used to receive incoming XML) was . > Using the XML Class It's time to start using some XML! Nearly everything you do with XML in Flash involves the XML class and falls into one of the. var myXML :XML = new XML( ); myXML.onLoad = init; myXML.load("http://somedomain.com/info .xml& quot;); As the next-to-last line shows, when the XML document

Ngày đăng: 24/12/2013, 07:17

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan