First, create XML file named test.xml and add text as below
- <document>
 - <head>Header</head>
 - <body>
 - <content>
 - <no>1</no>
 - <text>Content 1</text>
 - </content>
 - <content>
 - <no>2</no>
 - <text>Content 2</text>
 - </content>
 - </body>
 - <foot>Footer</foot>
 - </document>
 
ต่อมา ใส่โค้ดด้านล่างนี้ในสคริปต์ของคุณ
Next, insert the code below to your script
- function loadXML(){
 - var xmlLoader:URLLoader = new URLLoader();
 - xmlLoader.addEventListener(Event.COMPLETE, showXML);
 - xmlLoader.load(new URLRequest("test.xml"));
 - }
 - function showXML(e:Event):void {
 - XML.ignoreWhitespace = true;
 - var doc:XML = new XML(e.target.data);
 - trace(doc.head);
 - trace(doc.body.content.length());
 - for (var i:int=0; i < doc.body.content.length(); i++) {
 - trace("Body: "+ doc.body.content[i].text);
 - trace("Body: "+ doc.body.content[i].no);
 - }
 - trace(doc.foot);
 - }
 
บรรทัดที่ 4, ข้อความถูกโหลดจาก test.xml
At line 4, Text is loaded from test.xml
บรรทัดที่ 8, ตัวแปร XML ถูกนิยามพร้อมกับใช้ข้อมูลที่ถูกโหลดเข้ามา
At line 8, XML variable is defined with using loaded data
บรรทัดที่ 9-15, ทำการแสดงค่าของแต่ละอีลิเมนต์
At line 9-15, The value of each element is printed
หมายเหตุ:
ใช้ doc.element_name เพื่ออ่านค่าของอีลิเมนต์ในระดับแรก เช่น doc.head
ต่อท้ายด้วย .element_name เพื่ออ่านค่าในระดับถัดไป เช่น doc.body.content
ใช้ .element_name[index] เพื่ออ่านค่าอีลิเมนต์ที่ซ้ำกัน เช่น  doc.body.content[i]
Notice: 
Use doc.element_name to get value of element in first level such as doc.head
Append .element_name to get value of element in next level such as doc.body.content
Use .element_name[index] to get value of element that is duplicated such as doc.body.content[i]
เรียกฟังก์ชั่น loadXML จากคอนสตรัคเตอร์ของคลาส แล้วกดปุ่ม Ctrl+Enter เพื่อรัน
Call loadXML from your class constructor then press Ctrl+Enter to run
หน้าต่าง output จะแสดงข้อความตามด้านล่าง
The output window will show text as
Header
2
Body: Content 1
Body: 1
Body: Content 2
Body: 2
Footer
หมายเหตุ: อย่าลืม import flash.net.*;
Notice: you must import flash.net.*;  
No comments:
Post a Comment