Flex4 和 ActionScript3 支持 XML 。Flex中有内置的XML和XMLList、XMLListCollection 。
这里新建一个MXML程序,其中将体现一些包括排序在内的XML基本操作。
<?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"
width="100%" height="100%"
initialize="init()">
<fx:Script>
<![CDATA[
//导入所需的类
import mx.collections.XMLListCollection;
import mx.collections.Sort;
import mx.collections.SortField;
//创建XML对象、在AS中直接编写
private var _projectsXML:XML =
<projects>
<project id="1" name="Proj1">
<task id="1">
<name>task 1 message</name>
<notes>task 1 note</notes>
</task>
<task id="2">
<name>task 2 message</name>
<notes>task 2 note</notes>
</task>
</project>
<project id="2" name="Proj2">
<task id="3">
<name>task 3 message</name>
</task>
<task id="4">
<name>task 4 message</name>
<notes>task 4 note</notes>
</task>
</project>
</projects>;
private function init():void {
var output:String = "";
output += "全部的 XML:\n" + _projectsXML;
output += "\n\n使用 E4X 和 XMLList:\n";
output += _projectsXML.project[0].task[0].name + "\n"; //使用E4X 直接得到子节点
output += _projectsXML.project.(@name=="Proj2").task.(@id==3).name;
var projects:XMLList = _projectsXML.children();//得到一个子节点集合
for each (var project:XML in projects) {
output += "Project: " + project.@name + "\n";//使用句点语法检索E4x、特性和子元素的值。对于特性值前面加@即可。
for each (var task:XML in project.task) {
output += " Task " + task.@id + ": " + task.name;
if (task.hasOwnProperty('notes')) {//使用 hasOwnProperty来检查是否有此属性
output += " (" + task.notes + ")";
}
output += "\n";
}
}
output += "\n熟悉 XMLListCollection并且进行简单排序:\n"
var allTasks:XMLListCollection = new XMLListCollection(
_projectsXML.descendants("task"));//取节点名为Task的所有节点
var sort:Sort = new Sort();
sort.fields = [new SortField("name",true)];//使用排序函数
allTasks.sort = sort;
allTasks.refresh();//刷新集合并输出
for each (var sortedTask:XML in allTasks) {
output += sortedTask.name + "\n";
}
outputTA.text = output;
}
]]>
</fx:Script>
<s:TextArea id="outputTA" width="100%" height="100%"/>
</s:Application>