Converting XML to objects using the Flex HTTPService MXML tag
The following example shows how you can convert an XML file loaded at run-time using the HTTPService tag, into an ActionScript Object by simply setting the resultFormat property to “object”.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/19/converting-xml-to-objects-using-the-flex-httpservice-mxml-tag/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="serv.send();">
<mx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
private function serv_result(evt:ResultEvent):void {
var resultObj:Object = evt.result;
/* Assign the values... */
nameText.text = resultObj.album.name;
img0Text.text = resultObj.album.images.image[0];
img1Text.text = resultObj.album.images.image[1];
img2Text.text = resultObj.album.images.image[2];
}
private function serv_fault(evt:FaultEvent):void {
/* Show the error label. */
error.text += evt.fault.faultString;
error.visible = true;
/* Hide the form. */
form.visible = false;
}
]]>
</mx:Script>
<mx:String id="XML_URL">album.xml</mx:String>
<mx:HTTPService id="serv"
url="{XML_URL}"
resultFormat="object"
result="serv_result(event);"
fault="serv_fault(event);" />
<mx:ApplicationControlBar dock="true">
<mx:Label text="{XML_URL}" />
</mx:ApplicationControlBar>
<mx:Label id="error"
color="red"
fontSize="36"
fontWeight="bold"
visible="false"
includeInLayout="{error.visible}"/>
<mx:Form id="form"
includeInLayout="{form.visible}">
<mx:FormItem label="resultObj.album.name:">
<mx:Label id="nameText" />
</mx:FormItem>
<mx:FormItem label="resultObj.album.images.image[0]:">
<mx:Label id="img0Text" />
</mx:FormItem>
<mx:FormItem label="resultObj.album.images.image[1]:">
<mx:Label id="img1Text" />
</mx:FormItem>
<mx:FormItem label="resultObj.album.images.image[2]:">
<mx:Label id="img2Text" />
</mx:FormItem>
</mx:Form>
</mx:Application>
<?xml version="1.0" encoding="utf-8"?>
<album>
<name>One</name>
<images>
<image>image1.jpg</image>
<image>image2.jpg</image>
<image>image3.jpg</image>
</images>
</album>
View source is enabled in the following example.
Tagged with: resultFormat
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
20 Responses to Converting XML to objects using the Flex HTTPService MXML tag
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


What about strong typing, e.g.
What’s the syntax?
mae,
I’m not sure of the *best* way, but I’ve found this works (but almost feels a little “hacky” to me):
MyCustomObject.as
package { import mx.utils.ObjectProxy; public class MyCustomObject extends Object { public var name:String; public var images:ObjectProxy; public static function create(value:Object):MyCustomObject { var co:MyCustomObject = new MyCustomObject(); co.name = value.name; co.images = value.images; return co; } } }main.mxml — snippet
private function serv_result(evt:ResultEvent):void { var resultObj:MyCustomObject = MyCustomObject.create(evt.result.album as Object); /* Assign the values... */ nameText.text = resultObj.name; img0Text.text = resultObj.images.image[0]; img1Text.text = resultObj.images.image[1]; img2Text.text = resultObj.images.image[2]; }Mae,
You may want to ask on FlexCoders and see if anybody has a better solution.
Peter
After a bit of Googling, this looks like it could do the trick. Darron Schall has an excellent looking example in his blog, “Convert Generic Objects into Class Instances”.
Peter
peter,
Thanks. I saw that article a while back and didn’t understand it’s importance (I’m new at flex/actionscript). I’ll give it a shot.
Thanks again!
Peter,
I’m getting the following error with Darron’s code (I emailed him as well).
I’m returning an object from an ASP.Net Web service.
Any ideas? My
resultFormatis object.Thanks.
mae,
Yeah, I’m seeing the same error (End of File). Let me know what you find out from Darron.
Peter
Mae and Peterd,
I’m also encountering this issue… has anyone figured why this message occurs? Thanks!
Larry
Are you using an ArrayCollection and or are you using the default makeObjectsBindable and the result contains an Array? In my case, I believe that is where it choking.
Hi Peter
i read the other topic on your blog, we can use the function at the below to get the xml’s data on the data grid
private function resultHandler(event:ResultEvent):void { xmlData = event.result.mynode.childnode.source as Array; xmlDataAC.source = xmlData; }but in this case the xml format is has different child node
One
image1.jpg
image2.jpg
image3.jpg
can i still use
xmlData = event.result.album.name.source as Array;andxmlData2 = event.result.album.image.source as Array;to get the data ?? i have tried that they were not work. do you have any suggestion to get the data from different node easily ?? becauseimg0Text.text = resultObj.album.images.image[0];is so hard to use when my xml has alot/ unknow lenght node.Peter,
I’m having an issue with understanding Flex’s HttpService calls. I’m looking to do something similar to an HTML Select with my form. I currently have 1 List box and 3 comboBox’s receiving XML data from my MySQL DB.
It is currently just populating the Label, however when I go to insert/update to the database I want to insert the Value (or Key) and not the label. How could I do this? I thought if I returned the result from the HTTPService as a result it would look more like an HTML Select, however I can’t think of how the combobox or list will know what to submit when a particular Label is selected… since they are usually a selectedItem or selectedIndex.
Sorry for my confusing text either way, any help would be greatly appreciated.
Andy
Andrew,
I typically use <ComboBox>.selectedItem.<fieldName>, or, something like the following:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Array id="arr"> <mx:Object label="One" data="1" /> <mx:Object label="Two" data="2" /> <mx:Object label="Three" data="3" /> <mx:Object label="Four" data="4" /> </mx:Array> <mx:ComboBox id="comboBox" dataProvider="{arr}" /> <mx:Label text="comboBox.selectedItem.label={comboBox.selectedItem.label}" /> <mx:Label text="comboBox.selectedItem.data={comboBox.selectedItem.data}" /> </mx:Application>Hope that helps,
Peter
Peter,
I totally understand how that works… but how can I do that when I’m returning XML from a DB?
What would my XML need to look like? Also, wouldn’t I have to put the XML into a XMLListCollection or XMLList?
My XML is currently returning something like this:
Peter
Andrew
….
and so on…..
Would I want to include the employees primary key in the XML?
Peter
20
Andrew
2
Basically, I understand the logic behind .selectedItem…. but am really confused how to work with the XML as supposed to hardcoding my Object Array.
Thanks!
to simplify what I’m saying… i want to mimic the:
<mx:Array id="arr"> <mx:Object label="One" data="1" /> <mx:Object label="Two" data="2" /> <mx:Object label="Three" data="3" /> <mx:Object label="Four" data="4" /> </mx:Array>but coming from an HTTPService from a .php file outputting XML
Andrew,
You could try setting the
resultFormatproperty on the HTTPService tag to “array” when loading an XML file and see what type/format of an ArrayCollection object that returns. To get at the underlying Array object, you would just access the ArrayCollection object’ssourceproperty.Apart from that, if you have a specific format you want, I’d suggest just writing your own code. Take the last result from the HTTPService tag, and loop over the ArrayCollection/XML results and construct your own custom array of objects in the specific format you need.
Peter
Nice example.
But my XML file have hyphens in the tags. And i cant get it to work.
How would i do if for example the album tags instead of <album> was <album-album>?
@Simon,
Try this:
Assuming you had the following XML packet:
Peter
Hi,
Nice tutorial. But I also want to validate my XML against a given XSD schema. Could you please tell me about how to do that.
Thanks,
Amit.
Thank you so much for this example…. I was struggling to get the datas in dataGrid…. Now im clear. Thanq.
Excelent!! thanks Peter, i have a little question (too late XD):
if on the xml file i have more than one album, something like:
One
image1.jpg
image2.jpg
image3.jpg
Two
asdf.jpg
qwer.jpg
zcxv.jpg
How could i acces to the album Two, image 3???
How does the object would be?
Maybe something like:
resultObj.albums.album[2].images.image[3]; ?????
thanks.