1.使用嵌入的XML数据
(1).在工程中新建XML文件,路径自定义,例如:assets/inventory.xml
<?xml version="1.0" encoding="utf-8"?>
<groceries>
<catName>Dairy</catName>
<prodName>Milk</prodName>
<imageName>assets/dairy_milk.jpg</imageName>
<cost>1.20</cost>
<listPrice>1.99</listPrice>
<isOrganic>true</isOrganic>
<isLowFat>true</isLowFat>
<description>Direct from California where cows are happiest!</description>
</groceries>
(2).在mxml的<fx:Declarations></fx:Declarations>标签中加入
<fx:XML id="groceryInventory" source="assets/inventory.xml"/>
以后就可以引用groceryInventory的数据,数据来源于assets/inventory.xml。XML改成Model表示把XML转换成对象,也可以使用。
引用代码,比如在creationComplete处理函数中加入:
trace(groceryInventory.catName);//访问catName属性
theProduct = Product.buildProduct( groceryInventory ); //使用 groceryInventory
2.运行时加载XML
HttpService组件可以让应用程序访问URL获取数据。默认返回数据是以对象返回的。但是可以选择对象、XML和文本等格式来处理数据。
步骤:
(1)创建一个HttpService对象;
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
<s:HTTPService id="categoryService"
url="http://www.flexgrocer.com/category.xml"
resultFormat="e4x"
result="handleCategoryResult(event)"/>
</fx:Declarations>
url 可以是http url 也可以是文件系统路径。
(2)条用对象的send()方法;
categoryService.send();
(3)使用返回的数据。
在上面HttpService对象中result使用下面事件函数处理
private function handleCategoryResult(event:ResultEvent):void{
categories = new XMLListCollection( event.result.category );
}