Flex将XML数据转换ArrayList

ph.xml如下:

<?xml version="1.0" encoding="utf-8"?>


<data value="XX通讯录">
	<user>
		<bn>办公室</bn>
		<xm>冯XX</xm>
		<bg>677598XX</bg>
		<tel>130760616XX</tel>
	</user>
		<user>
		<bn>销售处</bn>
		<xm>李XX</xm>
		<bg>427598XX</bg>
		<tel>158760616XX</tel>
	</user>
		<user>
		<bn>技术部</bn>
		<xm>张XX</xm>
		<bg>427598XX</bg>
		<tel>137760616XX</tel>
	</user>
		<user>
		<bn>财务部</bn>
		<xm>孙XX</xm>
		<bg>522598XX</bg>
		<tel>133760616XX</tel>
	</user>
</data>

flex实现如下:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
	<s:layout>
		<s:BasicLayout/>
	</s:layout>
	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.collections.ArrayList;
			import mx.controls.Alert;
			import mx.rpc.events.ResultEvent;

			private var d : XML;

			protected function button1_clickHandler(event:MouseEvent):void
			{
				http.send();
			}
			
			
			public var arL : ArrayList = new ArrayList();
			public var arrC : ArrayCollection = new ArrayCollection();
			
			protected function http_resultHandler(event:ResultEvent):void
			{
				d = event.result as XML;
				
				arL = getArrayListForXml(d.children());
				var i:int;
				var len:int = arL.length;
				for(i = 0; i < len; i++)
				{
					arrC.addItem({bn:arL.getItemAt(i).bn,xm:arL.getItemAt(i).xm,bg:arL.getItemAt(i).bg,tel:arL.getItemAt(i).tel});
					
				}
				dataGrid1.dataProvider = arrC;
			}

			
			//XML转换成ArrayList
			private function getArrayListForXml(data:XMLList):ArrayList
			{
				var arrList : ArrayList = new ArrayList();
				if(data != null)
				{
					for(var i:int = 0; i < data.length(); i++)
					{
						var obj : Object = new Object();
						for(var j:int = 0; j < data[i].children().length(); j++)
						{
							var dataColoum : String = data[i].children()[j].localName();
							obj[dataColoum] = data[i].children()[j].toString();
						}
						arrList.addItem(obj);
					}
				}
				return arrList;
			}
			

		]]>
	</fx:Script>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
		<s:HTTPService id="http" url="ph.xml" resultFormat="e4x" result="http_resultHandler(event)">
			
		</s:HTTPService>
	</fx:Declarations>
	<mx:DataGrid x="37" y="36" width="358" height="193" id="dataGrid1">
		<mx:columns>
			<mx:DataGridColumn headerText="部门名称" dataField="bn"/>
			<mx:DataGridColumn headerText="姓名" dataField="xm"/>
			<mx:DataGridColumn headerText="办公电话" dataField="bg"/>
			<mx:DataGridColumn headerText="手机号码" dataField="tel"/>
		</mx:columns>
	</mx:DataGrid>
	<s:Button x="430" y="36" label="导入数据" click="button1_clickHandler(event)"/>
</s:Application>

效果如下:


Flex将XML数据转换ArrayList
 

相关推荐