intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Using the XML Class

Chia sẻ: Qweqwdasd Qweqdasda | Ngày: | Loại File: PDF | Số trang:17

133
lượt xem
47
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Sử dụng Class XML Đó là thời gian để bắt đầu sử dụng một số XML! Gần như tất cả mọi thứ bạn làm với XML trong Flash bao gồm các lớp học XML và thuộc một trong các loại sau: định dạng XML, phân tích cú pháp XML (chiết xuất thông tin), bốc XML, hoặc gửi XML.

Chủ đề:
Lưu

Nội dung Text: Using the XML Class

  1. < 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: Kelly Makar Free Makar
  2. 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 = " Kelly Makar Free Makar"; 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
  3. returns Kelly Makar 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: Free Makar attributes: This property returns an associative array of attribute names. For example: myXML.firstChild.firstChild.nextSibling.attributes.Gender
  4. 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
  5. 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("Hi!"); 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:
  6. var URL:String = "http://www.myDomain.com/UserLogin.asp"; function init () { trace(objToReceive); } var xmlToSend:String = "Jobemhayes"; 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.
  7. 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.
  8. 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: jobem jobe@electrotank.com secret If the user was registered properly, this page (AddUser.asp) returns the following result: User Inserted If a user of the same name already exists, the ASP page returns this result instead: User Exists
  9. The UserLogin.asp page accepts an XML document structured as follows: jobem secretword If the information provided was correct, this page returns the following result: Login Correct If the information provided was incorrect, the page returns this result instead: Login Incorrect 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
  10. 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.
  11. 4. After the login_btn event handler, add the following script: 5. 6. register_btn.onRelease = function() { 7. 8. _root.gotoAndStop("Register"); 9. 10. }; 11. This script adds an onRelease event handler to the register_btn button instance. The user clicks this button to go to the register frame to register a new account. 5. Move the playhead to the frame labeled Login. At this label are two TextInput component instances (username_ti and password_ti) and a button 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 returns an answer to let you know whether the user provided the correct information. This URL should include the full path to the UserLogin.asp file that you uploaded. 6. With the same frame still selected, add the following script: 7. 8. 9. var objToReceive:XML;
  12. 10. 11. submit_btn.onRelease = function() { 12. 13. var xmlToSend:String = "" + username_ti.text + "" 14. 15. + password_ti.text + ""; 16. 17. var objToSend:XML = new XML(xmlToSend); 18. 19. objToReceive = new XML(); 20. 21. objToReceive.onLoad = loginResponse; 22. 23. objToSend.sendAndLoad(loginURL, objToReceive); 24. 25. _root.gotoAndStop("Waiting"); 26. 27. }; 28. The first line of this script creates a variable named objToReceive, which will eventually hold an XML object. Next, a function is defined. This function is called when the user clicks the Submit button, with an instance name 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 XML- formatted string we just created. The reason for doing this is that the sendAndLoad() method only works 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 sendAndLoad() method by 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.
  13. 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 created 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 can be 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 in Step 6: 8. 9. function loginResponse() { 10. 11. var response:String = objToReceive.firstChild.firstChild.firstChild.nodeValue; 12. 13. if (response == "Login Correct") { 14. 15. _root.gotoAndStop("Login Success"); 16. 17. } else if (response == "Login Incorrect") { 18. 19. _root.gotoAndStop("Login Failed"); 20. 21. } 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 page is in this format:
  14. Login Correct|Login Incorrect As a result, response will have a value of either Login Correct or Login Incorrect, depending on what's extracted from this XML document. An if statement then uses this value to send the timeline to the frame labeled either Login Success or Login Failed. This action moves from the Waiting frame, which is used as an interim location while waiting for a response from the server. 8. Move the playhead to the frame labeled Register. At this label are three TextInput component instances (username_ti, email_ti, and password_ti) and a button with an instance name 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.
  15. 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 uploaded. 9. With the same frame still selected, add the following script: 10. 11. 12. var objToReceive:XML; 13. 14. submit_btn.onRelease = function() { 15. 16. var XMLtoSend:String = "" + username_ti.text + "" 17. 18. + email_ti.text + "" + password_ti.text + ""; 19. 20. var objToSend:XML = new XML(XMLtoSend); 21. 22. objToReceive = new XML(); 23. 24. objToReceive.onLoad = registrationResponse; 25. 26. objToSend.sendAndLoad(registrationURL, objToReceive); 27. 28. _root.gotoAndStop("Waiting"); 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 script will parse this 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
  16. 10. 10. Add the following function definition after the one you added in Step 9: 11. 12. function registrationResponse() { 13. 14. var response:String = objToReceive.firstChild.firstChild.firstChild.nodeValue; 15. 16. if (response == "User Inserted") { 17. 18. _root.gotoAndStop("Registration Success"); 19. 20. } else if (response == "User Exists") { 21. 22. _root.gotoAndStop("Registration Failed"); 23. 24. } 25. 26. } 27. The function in this step is called when the last byte of information is loaded into objToReceive. This function is similar to the loginResponse() function defined in Step 7. Remember that the AddUser.asp page returns a document of this format: User Inserted|User Exists As a result, response will have a value of either User Inserted or User Exists, depending on what is extracted from this XML document. An if statement then uses this value to send the timeline to the frame labeled Registration Success or the frame labeled Registration Failed. 11. Choose Control > Test Movie to test your work. Click the Register button and submit some information. Reopen the movie and then try to log in.
  17. You have just created a simple application that illustrates some uses of the XML object. Test it a few times to make sure that you're comfortable with the ActionScript. 12. Close the test movie and save your work as loginRegister2.fla. Now you're ready to start creating some advanced data-driven applications. < Day Day Up >
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
4=>1