วันนี้เรามาลองใช้ XML ใน Flash กันดูนะ… ซึ่ง XML มีลักษณะแบบนี้…
XML
1 2 3 4 5 6 7 8 9 10 | <?xml version="1.0" encoding="utf-8"?> <data> <name>Name</name> <age>25</age> <bag> <item id="1">Value1</item> <item id="2">Value2</item> <item id="3">Value3</item> </bag> </data> |
จะเห็นรูปแบบ XML ว่าคล้ายๆ HTML ที่มี tag เปิด/ปิด ครอบข้อมูลอยู่…
ซึ่งเราจะเรียกว่า element
เมื่อแยกส่วนออกมาก็จะได้ดังนี้…
data ที่เราเห็นอยู่นอกสุดนั้นคือ root element
name, age และ bag เราจะเรียกว่า child element
item ทั้ง 3 ตัว ก็คือ (sub) child element (ของ bag) เช่นกัน…
แล้ว item ทั้ง 3 ตัวนั้นมี attribute ชื่อ id ซึ่งมีค่า 1, 2 และ 3 ตามลำดับ…
แล้ว id แต่ละตัวมีค่า Value1, Value2 และ Value3 ตามลำดับเช่นกัน…
…
เมื่อลองมาเขียน ActionScript เพื่อที่จะดึงข้อมูลใน XML นี้ออกมาใช้งาน…
ซึ่งใน ActionScript นี้จะมองแต่ละ element เป็น node แทน…
ActionScript 2.0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | var xml:XML = new XML('<?xml version="1.0" encoding="utf-8"?><data><name>Name</name><age>25</age><bag><item id="1">Value1</item><item id="2">Value2</item><item id="3">Value3</item></bag></data>'); trace("root node = " + xml.firstChild); trace("node 1 = " + xml.firstChild.childNodes[0]); trace("node 2 = " + xml.firstChild.childNodes[1]); trace("node 3 = " + xml.firstChild.childNodes[2]); trace("//"); trace("node 1: value = " + xml.firstChild.childNodes[0].firstChild.nodeValue); trace("node 2: value = " + xml.firstChild.childNodes[1].firstChild.nodeValue); trace("//"); trace("node 3.1: attribute id = " + xml.firstChild.childNodes[2].childNodes[0].attributes.id); trace("node 3.1: value = " + xml.firstChild.childNodes[2].childNodes[0].firstChild.nodeValue); trace("//"); trace("node 3.2: attribute id = " + xml.firstChild.childNodes[2].childNodes[1].attributes.id); trace("node 3.2: value = " + xml.firstChild.childNodes[2].childNodes[1].firstChild.nodeValue); trace("//"); trace("node 3.3: attribute id = " + xml.firstChild.childNodes[2].childNodes[2].attributes.id); trace("node 3.3: value = " + xml.firstChild.childNodes[2].childNodes[2].firstChild.nodeValue); trace("//"); |
เมื่อ test movie แล้วจะได้ผลดังนี้…
Output
root node = <data><name>Name</name><age>25</age><bag><item id="1">Value1</item><item id="2">Value2</item><item id="3">Value3</item></bag></data> node 1 = <name>Name</name> node 2 = <age>25</age> node 3 = <bag><item id="1">Value1</item><item id="2">Value2</item><item id="3">Value3</item></bag> // node 1: value = Name node 2: value = 25 // node 3.1: attribute id = 1 node 3.1: value = Value1 // node 3.2: attribute id = 2 node 3.2: value = Value2 // node 3.3: attribute id = 3 node 3.3: value = Value3 //
…
โดยรวมจะเห็นได้ว่า รูปแบบของ XML ง่ายต่อการจัดรูปแบบข้อมูล เป็นมาตรฐานที่เข้าใจในวงกว้าง… จึงเป็นที่นิยมในการนำไปทำระบบแสดงผล ข้อมูลต่างๆ หลายรูปแบบ…
เช่น RSS Feed, Photo Gallery, Config File, Data File
// XML Tutorial (w3schools.com)


