Loading XML at run-time using the mx:HTTPService tag
In the previous post we looked at how to load an XML document in at compile-time and have it embedded in our Flex application. But that technique really only works if the XML data in question never changes. What if you had an XML document that was constantly changing on a daily, or hourly, basis. For example, consider an RSS reader application. If the XML was loaded and embedded in the XML document at compile-time, the RSS would never get updated. And while that may be good in some cases (such as a kiosk, or somewhere without an internet connection where you wanted to display static information), in many cases it may not work.
So, lets take a look at using the mx:HTTPService tag to dynamically load an XML file.
The following example dynamically loads an XML file at run-time using the mx:HTTPService tag, rather than using mx:XML and grabbing the data at compile-time:
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/07/27/loading-xml-at-run-time-using-the-mxhttpservice-tag/ -->
<mx:Application name="HTTPService_resultFormat_test_2"
xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="top"
backgroundColor="white"
creationComplete="tempXML.send();">
<mx:HTTPService id="tempXML"
url="xml/cuePoints.xml"
resultFormat="e4x" />
<mx:XMLListCollection id="cuePointXMLList"
source="{tempXML.lastResult.CuePoint}" />
<mx:XMLListCollection id="parametersXMLList"
source="{dataGrid.selectedItem.Parameters.Parameter}" />
<mx:Script>
<![CDATA[
private function parametersLabelFunction(item:Object, column:DataGridColumn):String {
return item.Parameters.Parameter.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="dataGrid"
dataProvider="{cuePointXMLList}"
width="100%"
rowCount="{cuePointXMLList.length + 1}">
<mx:columns>
<mx:DataGridColumn id="timeCol"
dataField="Time"
headerText="Time (ms):"
sortCompareFunction="numericSortCompareFunction" />
<mx:DataGridColumn id="typeCol"
dataField="Type"
headerText="Type:" />
<mx:DataGridColumn id="nameCol"
dataField="Name"
headerText="Name:" />
<mx:DataGridColumn id="parametersCol"
dataField="Parameters"
headerText="Parameters:"
labelFunction="parametersLabelFunction" />
</mx:columns>
</mx:DataGrid>
<mx:DataGrid id="parametersDataGrid"
dataProvider="{parametersXMLList}"
width="100%"
visible="{parametersXMLList.length > 0}"
rowCount="{parametersXMLList.length + 1}">
<mx:columns>
<mx:DataGridColumn id="parameterNameCol"
dataField="Name"
headerText="Parameter Name:" />
<mx:DataGridColumn id="parameterValueCol"
dataField="Value"
headerText="Parameter Value:" />
</mx:columns>
</mx:DataGrid>
</mx:VBox>
</mx:Application>
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!-- http://blog.flexexamples.com/2007/07/27/loading-xml-at-run-time-using-the-mxhttpservice-tag/ -->
<FLVCoreCuePoints version="1">
<CuePoint>
<Time>0</Time>
<Type>event</Type>
<Name>slide1</Name>
<Parameters>
<Parameter>
<Name>id</Name>
<Value>value</Value>
</Parameter>
</Parameters>
</CuePoint>
<CuePoint>
<Time>5000</Time>
<Type>event</Type>
<Name>slide2</Name>
<Parameters>
<Parameter>
<Name>param1</Name>
<Value>value1</Value>
</Parameter>
<Parameter>
<Name>param2</Name>
<Value>value2</Value>
</Parameter>
</Parameters>
</CuePoint>
<CuePoint>
<Time>20000</Time>
<Type>event</Type>
<Name>slide3</Name>
</CuePoint>
</FLVCoreCuePoints>
View source is enabled in the following example.
The first thing you notice is that the code is nearly identical to the previous example which used mx:XML. The subtle differences are that instead of mx:XML we used mx:HTTPService to get the data. Also, we now listen for the creationComplete event for on the Application tag where we trigger the XML loading using the HTTPService.send() method. Finally, the locations of the files changed slightly. Now instead of the XML being calculated relative to the MXML file, the XML gets placed relative to the generated SWF file. All the other code stayed the same.
In case you’re curious, the sample XML document in question comes from a Quick Start I wrote for the Flash CS3 release, “Flash Quick Starts: Using the Adobe Flash CS3 Video Encoder“.
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.
15 Responses to Loading XML at run-time using the mx:HTTPService 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


Note: You also use tempXML.lastResult.CuePoint which is different from the last example.
First of all THANK YOU for this new tutorial Peterd.
Clean, simple…. to much simple maybee i cannot manage make him run.
Actually it runs but it is not loading anything.
I have reproduce your workflow again and again and same issue it wont Merge the xml files containing the value on stage.
FYI i have test others tutorial regarding rss reader or xml injections but still…
I have check the crossdomain system (for instance i have create a crossdomain.xml file in my local folder allowing “*” all the domains).
The only thing i am not sure off is my environment
I am log onto a Microsoft domain.
thank you for your help if you pass by :)
Gabriel.
Gabriel,
I uploaded a SWF and the full source code above.
The example works for me using the Flex 3.1 SDK, although I was getting some errors/warnings locally when I tested it. After uploading to the site and running over http:// rather than file:///, everything worked fine.
As for crossdomain issues, you shouldn’t need a crossdomain file if you’re just loading files from your own site. If you are loading remote XML from other sites, the other site would need the crossdomain file on their server.
Hope that helps,
Peter
Hi!
I learned a lot of things in your website, thanks for all. But I have a problem about loading external XML file to my SWF. Let me tell you my problem simplfy; I use mx:HTTPservice tag and write url=”http://www.mysite.com/gallery.xml” but when I try to run it, I get Error #2143 Security access url. My SWF and XML files are in same domain. So what is the problem, why I cannot load my XML file in same domain?
Please give me an idea about this problem, because very important..
Thanks!
Onur,
You should definitely be able to load XML from the same domain as your SWF file.
I’d start by trying to create a very simple test case and then try asking on a list like FlexCoders.
Peter
Peter,
I have used two mx:HTTPService tags. First one to invoke a JSP containing input form to take employee details and submit to bean for persisting into the database. Second one talks to a bean to fetch those persisted database records.
I am using mx:TabNavigator to separate these two functionalities and each tab contains a button – first has “Submit” and the second has “Show all employees”. “Submit” calls first HTTPService and “Show all employees” calls second HTTPService.
If I open this application and first create one employee, then navigate to second tab and click on “Show all employees” it pulls all records including latest record that was added. But if I add another employee and try refreshing by clicking “Show all employees” on second tab, it doesn’t refresh! Any idea why this is not refreshing?
Any help on this would be appreciated.
Best regards,
Jag
Hi,
If i create a projector through flash player 9(exe file) of above example it does not get updated and the change in data does not reflected on the application, but on the browser it worked properly..
what should i do if i want the exe file also to reflect the changes.
Piyush
how to connect our mxml file with htmt which is at web server ?
Hi, i ran into a problem. My dataGrid does not show any data, but it doesn’t give an erro either. I was using mx:XML instead of mx:HTTPService and it shows data but when i try to use httpservice, it’s like it isn’t loading anything! Can someone give a hint? Thanks in advance
Hi Rui,
Did you check the path of the xml file.. while using httpservice the xml needs to be relative to the .swf file and not the .mxml file
hey i try your source and i compile in linux ubuntu using gedit the result like this :
Running tool: Compile AS 3
Loading configuration file /opt/flex_sdk_3/frameworks/flex-config.xml
/home/antoni/Desktop/xml/src/main.mxml.swf (340292 bytes)
[RPC Fault faultString="Error #2148: SWF file file:///home/antoni/Desktop/xml/src/main.mxml.swf cannot access local resource file:///home/antoni/Desktop/xml/src/xml/cuePoints.xml. Only local-with-filesystem and trusted local SWF files may access local resources." faultCode="InvokeFailed" faultDetail="null"]
at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::invoke()
at mx.rpc.http::AbstractOperation/http://www.adobe.com/2006/flex/mx/internal::invoke()
at mx.rpc.http::AbstractOperation/sendBody()
at mx.rpc.http::HTTPService/send()
at main/___main_Application1_creationComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.core::UIComponent/dispatchEvent()
at mx.core::UIComponent/set initialized()
at mx.managers::LayoutManager/doPhasedInstantiation()
at Function/http://adobe.com/AS3/2006/builtin::apply()
at mx.core::UIComponent/callLaterDispatcher2()
at mx.core::UIComponent/callLaterDispatcher()
Done.
why?can someone tell me what wrong?
what should i do?
sorry if my english bad..i from indo..thanks for your answer
hmm..sorii for my question..now i know…whats wrong…
i forget something about xml for http service must running at webserver…
i try my apache and put in dir var/www/ it works when the app get data from xml source…
hehe
thanks :D
HI,
THANKS A LOT FOR UR BLOG. I HAVE CHECKING SO MANY SITE TO WORK WITH XML AND DATAGRID. EVERY WHERE I GOT FAILURE. BUT BASED ON THIS I GOT THE RESULT AND I AM VERY VERY THANKFUL TO YOU.
REGARDS
SRIKANTH
Hi,
can u help me about preloader,
I want to load multiple httpservice on preloader
thankyou
Hi,
can u help me about preloader custom skin
I want to load multiple httpservice on preloader
thankyou