FlexのちょっとしたTipsと講座(3) - XMLを使う
今回はXMLを使ってみる。例えば画像ビューアーを作るときに、HTMLから画像のURLを渡してもいいけど、XMLの方が後から何かを追加するときに楽だろうし、なによりプログラマーっぽくて格好いい(?)
images.xml
<?xml version="1.0" encoding="UTF-8"?> <images> <image> <headline> 懐かしのMAC OS9 </headline> <url> http://flex.dev.ws.ls/TestFlex/bin-debug/img/001.jpg </url> <description> 秋葉原の中古Mac店で発見。あまりの懐かしさに思わず写真を撮ってしまった。 </description> </image> <image> <headline> 本 </headline> <url> http://flex.dev.ws.ls/TestFlex/bin-debug/img/002.jpg </url> <description> 積まれっぱなしの本たち。 </description> </image> <image> <headline> ミスド </headline> <url> http://flex.dev.ws.ls/TestFlex/bin-debug/img/003.jpg </url> <description> ミスドで大量にドーナツを頼んでみた。 </description> </image> </images>
TestFlex.mxml
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:my="*" layout="absolute"> <my:Viewer url="http://flex.dev.ws.ls/TestFlex/bin-debug/images.xml" /> </mx:Application>
Viewer.as
package { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Loader; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; import mx.controls.Alert; import mx.core.UIComponent; public class Viewer extends UIComponent { public var url:String = ''; [ArrayElementType("Bitmap")] public var images:Array = null; public function Viewer() { images = new Array(); } override protected function commitProperties():void { var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, eventXmlLoadCompleted); loader.load(new URLRequest(url)); } protected function eventXmlLoadCompleted(event:Event):void { var loader:URLLoader = event.target as URLLoader; var images:XMLList = new XMLList(new XML(loader.data)); var image_nodes:XMLList = images.elements("image"); /* for (var i:int = 0; i < image_nodes.length(); ++i) { // こんな風にループさせる。取得はこんな。 # => image_nodes[i].url } */ /* for each(var item:Object in image_nodes.*::url) { // url だけ欲しい場合はこんな風にも書ける。 } */ var imgloader:Loader = new Loader(); imgloader.contentLoaderInfo.addEventListener(Event.COMPLETE, eventImageLoadCompleted); imgloader.load(new URLRequest(image_nodes[0].url)); Alert.show(image_nodes[0].url); } protected function eventImageLoadCompleted(event:Event):void { var loader:Loader = event.target.loader as Loader; var bitmapdata:BitmapData = new BitmapData(loader.width, loader.height); bitmapdata.draw(loader); var bitmap:Bitmap = new Bitmap(); bitmap.bitmapData = bitmapdata; addChild(bitmap); } } }
もうただの備忘録になっている気が…。