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:

View MXML

<?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/cuePoints.xml

<?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“.

15 thoughts on “Loading XML at run-time using the mx:HTTPService tag

  1. 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.

  2. 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

  3. 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!

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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

Comments are closed.