Get attribute names and values of xml in flex

One more sample to parse xml file with attributes in flex. Here is a sample, which displays the capital city and language of the selected country in the combobox. The details were getting through xml file with three attributes “country”, ”capital” and “language”.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="onLoad()">

 <mx:Script>
 <![CDATA[
 import mx.events.ListEvent;
 import mx.collections.XMLListCollection;
 import mx.rpc.events.FaultEvent;
 import mx.rpc.events.ResultEvent;
 import mx.rpc.http.HTTPService;

 /**
 * Call a service to get the xml data
 */
 private function onLoad():void {
 var service:HTTPService = new HTTPService;
 var localurl:String = "capitals.xml";

 service.url = localurl;
 service.resultFormat = "e4x";
 service.send();
 service.addEventListener(ResultEvent.RESULT, resultHandler);

 }

 /**
 * handling the result of the above service
 */
 private function resultHandler(event:ResultEvent):void {
 var allXml:XML = new XML(event.result);

 var xmlList:XMLListCollection = new XMLListCollection(allXml.record);

 countryCB.dataProvider = xmlList;
 display(xmlList[0]);
 }

 /**
 *     Displaying the data
 */
 private function display(xml:XML):void {

 var attNames:XMLList = xml.attributes();
 var str:String = '';
 for (var i:int=0; i<attNames.length(); i++) {

 str += attNames[i].name() + ' : ' + attNames[i] + '\n\n';
 }
 displayStr.text = str;

 }

 /**
 *     Event raised by changing the combo value selection
 */
 private function onChange(event:ListEvent):void {
 display(event.currentTarget.selectedItem);
 }
 ]]>
 </mx:Script>
 <mx:VBox  x="44" y="38" >
 <mx:ComboBox id="countryCB" minWidth="200" labelField="@country" change="onChange(event)"/>
 <mx:Text text="" id="displayStr" fontWeight="bold" />
 </mx:VBox>

</mx:Application>

country.xml


<countries>
 <record country="Abkhazia" capital="Sukhum" language="Abhazian,Russian,Cyrillic script"/>
 <record country="Afghanistan" capital="Kabul" language="Dari-Persian, Pashtu"/>
 <record country="Albania" capital="Tirana" language="Albanian"/>
 <record country="Algeria" capital="Algiers" language="Arabic"/>
 <record country="American Samoa" capital="Pago Pago" language="Samoan,English"/>
 <record country="Andorra" capital="Andorra la Vella" language="Catalan"/>
 <record country="Angola" capital="Luanda" language="Portuguese"/>
 <record country="Anguilla" capital="The Valley" language="English"/>
 <record country="Antigua and Barbuda" capital="Saint John's" language="English"/>
 <record country="Argentina" capital="Buenos Aires" language="Spanish"/>
 <record country="Armenia" capital="Yerevan" language="Armenian"/>
 <record country="Aruba" capital="Oranjestad" language="Dutch"/>
 <record country="Australia" capital="Canberra" language="English/ Aborginal native languages"/>
 <record country="Austria" capital="Vienna" language="German"/>
 <record country="Azerbaijan" capital="Baku" language="Azeri"/>
 <record country="Bahamas" capital="Nassau" language="English"/>
 <record country="Bahrain" capital="Manama" language="Arabic"/>
 <record country="Bangladesh" capital="Dhaka" language="Bengali"/>
 <record country="Barbados" capital="Bridgetown" language="English"/>
 <record country="Belarus" capital="Minsk" language="Belarusian,Russian"/>
 <record country="Belgium" capital="Brussels" language="Dutch,French,German"/>
 <record country="Belize" capital="Belmopan" language="English"/>
 <record country="Benin" capital="Porto-Novo" language="French"/>
 <record country="Bermuda" capital="Hamilton" language="English"/>
 <record country="Bhutan" capital="Thimphu" language="Dzongkha"/>
 <record country="Bolivia" capital="La Paz" language="Spanish, Quechua,Ayamara,Guaranj"/>
 <record country="Bosnia-Herzegovina" capital="Sarajevo" language="Bosnian, Serbian, Croatian"/>
 <record country="Botswana" capital="Gaborone" language="English"/>
 <record country="Brazil" capital="Brasilia" language="Portuguese"/>
 <record country="Brunei" capital="Bandar Seri Begawan" language="Malay"/>
 <record country="Bulgaria" capital="Sofia" language="Bulgarian"/>
 <record country="Burkina Faso" capital="Ouagadougou" language="French"/>
 <record country="Burundi" capital="Bujumbura" language="Kirundi"/>
 <record country="Cambodia" capital="Phnom Penh" language="Khmer"/>
 <record country="Cameroon" capital="Yaound�" language="French, English"/>
 <record country="Canada" capital="Ottawa" language="English, French"/>
 <record country="Cape Verde" capital="Praia" language="Portuguese"/>
 <record country="Cayman Islands" capital="George Town" language="English"/>
 <record country="Central African Republic" capital="Bangui" language="French, Sango"/>
 <record country="Chad" capital="N'Djamena" language="French, Arabic"/>
 <record country="Chile" capital="Santiago" language="Spanish"/>
 <record country="China (PRC)" capital="Beijing" language="mandarin"/>
 <record country="Christmas Island" capital="The Settlement" language="English"/>
 <record country="Cocos Islands" capital="West Island" language="English"/>
 <record country="Colombia" capital="Bogot�" language="Spanish"/>
 <record country="Comoros" capital="Moroni" language="Shikomor, Arabic, French"/>
 <record country="Congo" capital="Brazzaville" language="French"/>
 <record country="Congo (DRC)" capital="Kinshasa" language="French"/>
 <record country="Cook Islands" capital="Avarua" language="English"/>
 <record country="Costa Rica" capital="San Jos�" language="Spanish"/>
 <record country="C�te d'Ivoire" capital="Yamoussoukro" language="French"/>
 <record country="Croatia" capital="Zagreb" language="Croatian"/>
 <record country="Cuba" capital="Havana" language="Spanish"/>
 <record country="Cyprus" capital="Nicosia" language="Greek, Turkish"/>
 <record country="Czech Republic" capital="Prague" language="Czech"/>
 <record country="Denmark" capital="Copenhagen" language="Danish"/>
 <record country="Djibouti" capital="Djibouti City" language="Arabic, French"/>
 <record country="Dominica" capital="Roseau" language="English"/>
 <record country="Dominican Republic" capital="Santo Domingo" language="Spanish"/>
 <record country="East Timor" capital="D�li" language="Tetum, Portuguese"/>
 <record country="Ecuador" capital="Quito" language="Spanish"/>
 <record country="Egypt" capital="Cairo" language="Arabic"/>
 <record country="El Salvador" capital="San Salvador" language="Spanish"/>
 <record country="Equatorial Guinea" capital="Malabo" language="Spanish"/>
 <record country="Eritrea" capital="Asmara" language="Arabic, Tigrinya"/>
 <record country="Estonia" capital="Tallinn" language="Estonian"/>
 <record country="Ethiopia" capital="Addis Ababa" language="Amharic"/>
 <record country="Faroe Islands" capital="T�rshavn" language="Faroese"/>
 <record country="Fiji" capital="Suva" language="English, Fijian, Hindustani"/>
 <record country="Finland" capital="Helsinki" language="Finnish, Swedish"/>
 <record country="France" capital="Paris" language="French"/>
 <record country="French Guiana" capital="Cayenne" language="French"/>
 <record country="French Polynesia" capital="Papeete" language="French"/>
 <record country="Gabon" capital="Libreville" language="French"/>
 <record country="Gambia" capital="Banjul" language="English"/>
 <record country="Georgia" capital="T'bilisi" language="Georgian"/>
 <record country="Germany" capital="Berlin" language="German"/>
 <record country="Ghana" capital="Accra" language="English"/>
 <record country="Gibraltar" capital="Gibraltar" language="English"/>
 <record country="Greece" capital="Athens" language="Greek"/>
 <record country="Greenland" capital="Nuuk" language="Greenlandic, Danish"/>
 <record country="Grenada" capital="St. George's" language="English"/>
 <record country="Guadeloupe" capital="Basse-Terre" language="French"/>
 <record country="Guam" capital="Hag�t�a" language="English"/>
 <record country="Guatemala" capital="Guatemala City" language="Spanish"/>
 <record country="Guernsey" capital="St Peter Port" language="English"/>
 <record country="Guinea" capital="Conakry" language="French, Maninka, Susu, Pular"/>
 <record country="Guinea-Bissau" capital="Bissau" language="Portuguese"/>
 <record country="Guyana" capital="Georgetown" language="English"/>
 <record country="Haiti" capital="Port-au-Prince" language="French, Haitian Creole"/>
 <record country="Honduras" capital="Tegucigalpa" language="Spanish"/>
 <record country="Hungary" capital="Budapest" language="Hungarian"/>
 <record country="Iceland" capital="Reykjav�k" language="Icelandic"/>
 <record country="India" capital="New Delhi" language="Assamese,Bengali,English,Hindi,Kannada,Kashmiri,Konkani,Malayalam,Marathi"/>
 <record country="Indonesia" capital="Jakarta" language="Indonesian"/>
 <record country="Iran" capital="Tehran" language="Persian"/>
 <record country="Iraq" capital="Baghdad" language="Arabic"/>
 <record country="Ireland" capital="Dublin" language="Irish, English"/>
 <record country="Isle of Man" capital="Douglas" language="English, Manx"/>
 <record country="Israel" capital="Jerusalem" language="Hebrew, Arabic"/>
 <record country="Italy" capital="Rome" language="Italian"/>
 <record country="Jamaica" capital="Kingston" language="English"/>
 <record country="Japan" capital="Tokyo" language="Japanese"/>
 <record country="Jersey" capital="St. Helier" language="English, French, J�rriais"/>
 <record country="Jordan" capital="Amman" language="Arabic"/>
 <record country="Kazakhstan" capital="Astana" language="Kazakh, Russian"/>
 <record country="Kenya" capital="Nairobi" language="English, Swahili"/>
 <record country="Kiribati" capital="South Tarawa" language="English, Gilbertese"/>
 <record country="Korea (South)" capital="Seoul" language="Korean"/>
 <record country="Korea (North)" capital="P'y?ngyang" language="Korean"/>
 <record country="Kosovo" capital="Prishtin�" language="Albanian, Serbian"/>
 <record country="Kuwait" capital="Kuwait City" language="Arabic"/>
 <record country="Kyrgyzstan" capital="Bishkek" language="Kyrgyz, Russian"/>
 <record country="Laos" capital="Vientiane" language="Lao,Lao alphabet"/>
 <record country="Latvia" capital="Riga" language="Latvian"/>
 <record country="Lebanon" capital="Bairut" language="Arabic"/>
 <record country="Lesotho" capital="Maseru" language="Sesotho, English"/>
 <record country="Liberia" capital="Monrovia" language="English"/>
 <record country="Libya" capital="Tripoli" language="Arabic"/>
 <record country="Liechtenstein" capital="Vaduz" language="German"/>
 <record country="Lithuania" capital="Vilnius" language="Lithuanian"/>
 <record country="Luxembourg" capital="Luxembourg" language="Luxembourgish, German, French"/>
 <record country="Macedonia" capital="Skopje" language="Macedonian"/>
 <record country="Madagascar" capital="Antananarivo" language="Malagasy, French"/>
 <record country="Malawi" capital="Lilongwe" language="English, Chichewa"/>
 <record country="Malaysia" capital="Kuala Lumpur" language="Malay, English, Dhivehi"/>
 <record country="Maldives" capital="Mal�" language="Dhivehi"/>
 <record country="Mali" capital="Bamako" language="French, Bambara"/>
 <record country="Malta" capital="Valletta" language="Maltese"/>
 <record country="Marshall Islands" capital="Majuro" language="English, Marshallese"/>
 <record country="Martinique" capital="Fort-de-France" language="French"/>
 <record country="Mauritania" capital="Nouakchott" language="French, Arabi"/>
 <record country="Mauritius" capital="Port Louis" language="French"/>
 <record country="Mayotte" capital="Mamoudzou" language="French"/>
 <record country="Mexico" capital="Mexico City" language="Spanish"/>
 <record country="Micronesia" capital="Palikir" language="English"/>
 <record country="Moldova" capital="Chi?in?u" language="Romanian, French"/>
 <record country="Monaco" capital="" language=""/>
 <record country="Mongolia" capital="Ulaanbaatar" language="Mongolian"/>
 <record country="Montenegro" capital="Podgorica" language="Croatian"/>
 <record country="Montserrat" capital="Brades Estate" language="English"/>
 <record country="Morocco" capital="Rabat" language="Arabic"/>
 <record country="Mozambique" capital="Maputo" language="Portuguese"/>
 <record country="Myanmar" capital="Naypyidaw" language="Burmese"/>
 <record country="Namibia" capital="Windhoek" language="English, German, Afrikaans"/>
 <record country="Nauru" capital="no capital" language="English, Nauruan"/>
 <record country="Nepal" capital="Kathmandu" language="Nepali, Devanagari"/>
 <record country="Netherlands" capital="Amsterdam" language="Dutch"/>
 <record country="Netherlands Antilles" capital="Willemstad" language="Dutch"/>
 <record country="New Caledonia" capital="Noum�a" language="French"/>
 <record country="New Zealand" capital="Wellington" language="English, Maori"/>
 <record country="Nicaragua" capital="Managua" language="Spanish"/>
 <record country="Niger" capital="Niamey" language="French"/>
 <record country="Nigeria" capital="Abuja" language="English,Hausa,Igbo,Yoruba,Fulfulde,Broken English"/>
 <record country="Niue" capital="Alofi" language="Niuean, English"/>
 <record country="Norfolk Island" capital="Kingston" language="English"/>
 <record country="Northern Mariana Islands" capital="Saipan" language="English"/>
 <record country="Norway" capital="Oslo" language="Norwegian Bokmal, Norwegian Nynorsk"/>
 <record country="Oman" capital="Muscat" language="Arabic"/>
 <record country="Pakistan" capital="Islamabad" language="Urdu"/>
 <record country="Palau" capital="Melekeok" language="English, Palauan"/>
 <record country="Palestinian territories" capital="Ramallah" language="Arabic"/>
 <record country="Panama" capital="Panama City" language="Spanish"/>
 <record country="Papua New Guinea" capital="Port Moresby" language="English, Tok Pisin, Hiri Motu"/>
 <record country="Paraguay" capital="Asunci�n" language="Spanish, Guaranj"/>
 <record country="Peru" capital="Lima" language="Spanish"/>
 <record country="Philippines" capital="Manila" language="Filipino, English, Spanish"/>
 <record country="Pitcairn Islands" capital="Adamstown" language="English"/>
 <record country="Poland" capital="Warsaw" language="Polish"/>
 <record country="Portugal" capital="Lisbon" language="Portuguese"/>
 <record country="Puerto Rico" capital="San Juan" language="Spanish"/>
 <record country="Qatar" capital="Doha" language="Arabic"/>
 <record country="R�union" capital="Saint-Denis" language="French"/>
 <record country="Romania" capital="Bucharest" language="Romanian"/>
 <record country="Russia" capital="Moscow" language="Russian"/>
 <record country="Rwanda" capital="Kigali" language="French, Kinyarwanda, English"/>
 <record country="Saint-Pierre and Miquelon" capital="Saint-Pierre" language="French"/>
 <record country="Saint Helena" capital="Jamestown" language="English"/>
 <record country="Saint Kitts and Nevis" capital="Basseterre" language="English"/>
 <record country="Saint Lucia" capital="Castries" language="English"/>
 <record country="Saint Vincent and the Grenadines" capital="Kingstown" language="English"/>
 <record country="Samoa" capital="Apia" language="English"/>
 <record country="San Marino" capital="San Marino" language="Italian"/>
 <record country="S?o Tom� and Pr�ncipe" capital="S?o Tom�" language="Portuguese"/>
 <record country="Saudi Arabia" capital="Riyadh" language="Arabic"/>
 <record country="Senegal" capital="Dakar" language="French"/>
 <record country="Serbia" capital="Belgrade" language="Serbian"/>
 <record country="Seychelles" capital="Victoria" language="Seychellois Creole, French, English"/>
 <record country="Sierra Leone" capital="Freetown" language="English"/>
 <record country="Singapore" capital="" language="Malay, English, Mandarin, Tamil"/>
 <record country="Slovakia" capital="Bratislava" language="Slovak"/>
 <record country="Slovenia" capital="Ljubljana" language="Slovene"/>
 <record country="Solomon Islands" capital="Honiara" language="English"/>
 <record country="Somalia" capital="Mogadishu" language="Somali, Arabic"/>
 <record country="South Africa" capital="Pretoria (administrative capital), Cape Town (legislative capital), Bloemfo" language="English, Afrikaans, Zulu, Xhosa, Pedi, Sotho, Tswana, Venda, Tsonga, Swazi,"/>
 <record country="South Ossetia" capital="Tskhinval" language="Ossetian, Russian"/>
 <record country="Spain" capital="Madrid" language="Spanish/Galician, Catalan, Basque, Aranese"/>
 <record country="Sri Lanka" capital="Sri Jayawardenepura Kotte" language="Sinhala, Tamil"/>
 <record country="Sudan" capital="Khartoum" language="Arabic"/>
 <record country="Suriname" capital="Paramaribo" language="Dutch"/>
 <record country="Svalbard" capital="Longyearbyen" language="Norwegian"/>
 <record country="Swaziland" capital="Mbabane" language="English"/>
 <record country="Sweden" capital="Stockholm" language="Swedish"/>
 <record country="Switzerland" capital="Berne" language="German, French, Italian, Romansh"/>
 <record country="Syria" capital="Damascus" language="Arabic"/>
 <record country="Taiwan" capital="Taipei" language="Chinese"/>
 <record country="Tajikistan" capital="Dushanbe" language="Tajiki-Persian"/>
 <record country="Tanzania" capital="Dodoma" language="English"/>
 <record country="Thailand" capital="Bangkok" language="Thai"/>
 <record country="Togo" capital="Lom�" language="French"/>
 <record country="Tokelau" capital="" language="English"/>
 <record country="Tonga" capital="Nuku?alofa" language="Tongan"/>
 <record country="Transnistria" capital="Tiraspol" language="Russian, Ukrainian, Moldovan"/>
 <record country="Trinidad and Tobago" capital="Port of Spain" language="English"/>
 <record country="Tunisia" capital="Tunis" language="Arabic"/>
 <record country="Turkey" capital="Ankara" language="Turkish"/>
 <record country="Turkmenistan" capital="Ashgabat" language="Turkmen"/>
 <record country="Turks and Caicos Islands" capital="Cockburn Town" language="English"/>
 <record country="Tuvalu" capital="Fongafale (in Funafuti)" language="English"/>
 <record country="Uganda" capital="Kampala" language="English"/>
 <record country="Ukraine" capital="Kiev" language="Ukrainian"/>
 <record country="United Arab Emirates" capital="Abu Dhabi" language="Arabic"/>
 <record country="United Kingdom" capital="London" language="English, Welsh, Scots, Scots gaelic, Irish"/>
 <record country="United States" capital="Washington, D.C." language="English, Spanish, Cajun French, Hawaiian"/>
 <record country="Uruguay" capital="Montevideo" language="Spanish"/>
 <record country="Uzbekistan" capital="Tashkent" language="Uzbek"/>
 <record country="Vanuatu" capital="Port Vila" language="English"/>
 <record country="Vatican City" capital="" language="Latin"/>
 <record country="Venezuela" capital="Caracas" language="Spanish"/>
 <record country="Vietnam" capital="Hanoi" language="Vietnamese"/>
 <record country="Virgin Islands, British" capital="Road Town" language="English"/>
 <record country="Virgin Islands, US" capital="Charlotte Amalie" language="English"/>
 <record country="Wales" capital="Cardiff" language="English, Welsh"/>
 <record country="Wallis and Futuna" capital="Mat�'Utu" language="French"/>
 <record country="Western Sahara" capital="Laayoune (French transliteration)" language="Arabic"/>
 <record country="Yemen" capital="Sana�" language="Arabic"/>
 <record country="Zambia" capital="Lusaka" language="English"/>
 <record country="Zimbabwe" capital="Harare" language="English"/>

</countries>

In the creationComplete event of application an HttpService is sent and got country.xml as its response. To get the attributes details attributes() method of XML is used and it will return XMLList (this can also be achieved  by xml.@* and it will also return XMLList). To get the attribute name use name() method of XMLList and we can directly get the value of attribute from the list by index number.

We can modify the attributes names, count and values without change in the flex code, just by changing in the xml file. In this xml I just included country name, capital city and language and you can include values like currency, continent etc.,

Dynamic Width of ComboBox (Small Tweak)

Recently I have gone through a situation where there will be a ComboBox and it will have a list of data, some items will be too lengthy. And I have to show the width of Combo with the maximum size of the item in the dropdown list of Combo. First I thought I must iterate through through all the list items and get all the lenths and find the maximum length of the item. And then set that length to the comob. I search for samples with any simpler solution than the above, but all the people suggest the above process only.

Instead of doing the above process just remove the width property to the combo, instead provide minWidth (so that combo will show minimum width even there is no data). This solves my problem.

ComboBox ItemRenderer in flex DataGrid

For my Application I need a CobmboBox in Datagrid, and the combo will have a list of data. For this I googled a few samples. Here is a sample code, I modified it with my requirements.

My requirement is populate the Datagrid and there will be columns in datagrid that can be modified and updated to the database. To achive this I created ComboBox as ItemRenderer in the DataGridColumn. The data to the Combo must be dynamic.

Sample Code

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
 creationComplete="fillDataGrid()">

 <mx:Script>
 <![CDATA[
 import mx.collections.ArrayCollection;

 //  data provider of combo in datagrid, can get dynamic data by a service
 private var comboData:Array = new Array("Value0","Value1","Value2","Value3");

 /**
  *  populate the datagrid with sample data
  */
 private function fillDataGrid():void {
 var arrColl:ArrayCollection = new ArrayCollection;
 for (var i:int=0,j:int=0; i<50; i++,j++ ) {
 if ( j>3 ) j=0;

// create an object that will be provided to combo
 var obj:Object = new Object;
 obj.value = "Value"+j;
 obj.list = comboData;

// data is for first column, com is for the itemrenderer in that com object
 //value is slectedItem of combo and list is the provider of that combo
 arrColl.addItem({data:"data"+i, com:obj});

}

dg.dataProvider = arrColl;

}
 ]]>

</mx:Script>
 <mx:DataGrid id="dg" x="60" y="21" rowCount="5">
 <mx:columns>
 <mx:DataGridColumn dataField="data" headerText="Data" />
 <mx:DataGridColumn headerText="Value" itemRenderer="DynRender" />
 </mx:columns>
 </mx:DataGrid>
 </mx:Application>

DynRender.mxml


<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" horizontalScrollPolicy="off">

<mx:Script>
<![CDATA[

 override public function set data(value:Object):void {
   if(value != null) {
    super.data = value;
    mycombo.selectedItem=data.com.value;
   }

 }
 ]]>

</mx:Script>
<mx:ComboBox id="mycombo" dataProvider="{data.com.list}" width="100%"  />
</mx:Canvas>

The required data for the combo box is provided by the collection in ‘com’ item, In that we will provide the list item as dataprovider of the combo box. And value will the the selectedItem.