Flex动态读取XML文件并显示在DataGrid中
![](/Images/OutliningIndicators/ContractedBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<?xml version="1.0" encoding="utf-8"?>
<!-- 演示了Flex在编译阶段,利用mx:XML将XML数据读入,并且将其在DataGrid控件中显示-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="top"
backgroundColor="white">
<mx:XML id="tempXML"
source="assets/math.xml" />
<mx:XMLListCollection id="mathXMLList"
source="{tempXML.student}" />
<mx:XMLListCollection id="familyMembersXMLList"
source="{scoreDataGrid.selectedItem.familyMembers.familyMember}" />
<mx:Script>
<![CDATA[
private function getFamilyMembersCount(item:Object, column:DataGridColumn):String {
return item.familyMembers.familyMember.length();
}
private function numericSortCompareFunction(objA:Object, objB:Object):int {
var itemA:Number = parseInt(objA.Time.text()) as Number;
var itemB:Number = parseInt(objB.Time.text()) as Number;
if (itemA > itemB) {
return 1;
} else if (itemA < itemB) {
return -1;
} else {
return 0;
}
}
]]>
</mx:Script>
<mx:VBox>
<mx:DataGrid id="scoreDataGrid"
dataProvider="{mathXMLList}"
width="100%"
rowCount="{mathXMLList.length + 1}">
<mx:columns>
<mx:DataGridColumn id="nameCol"
dataField="name"
headerText="姓名"/>
<mx:DataGridColumn id="sexCol"
dataField="sex"
headerText="性别" />
<mx:DataGridColumn id="scoreCol"
dataField="score"
headerText="成绩"
sortCompareFunction="numericSortCompareFunction" />
<mx:DataGridColumn id="familyMembers"
dataField="familyMembers"
headerText="家庭成员个数"
labelFunction="getFamilyMembersCount" />
</mx:columns>
</mx:DataGrid>
<mx:DataGrid id="familyMembersDataGrid"
dataProvider="{familyMembersXMLList}"
width="100%"
visible="{familyMembersXMLList.length > 0}"
rowCount="{familyMembersXMLList.length + 1}">
<mx:columns>
<mx:DataGridColumn id="familyMemberNameCol"
dataField="name"
headerText="姓名" />
<mx:DataGridColumn id="familyMemberRelationshipCol"
dataField="relationship"
headerText="关系" />
</mx:columns>
</mx:DataGrid>
</mx:VBox>
</mx:Application>
xml文件如下:
![](/Images/OutliningIndicators/ContractedBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Math>
<student>
<name>lzx</name>
<sex>male</sex>
<score>85</score>
<familyMembers>
<familyMember>
<name>lyj</name>
<relationship>father</relationship>
</familyMember>
</familyMembers>
</student>
<student>
<name>zj</name>
<sex>female</sex>
<score>87</score>
<familyMembers>
<familyMember>
<name>zjfather</name>
<relationship>father</relationship>
</familyMember>
</familyMembers>
</student>
<student>
<name>cb</name>
<sex>male</sex>
<score>74</score>
</student>
</Math>