Build Internet has a brand new theme, and that's only the beginning. Read the full story or hide this bar

XML Basics with Flex 3

If you’re still using arrays and text files to load content, it’s time to upgrade.

With XML, you can condense a whole mess of seemingly unrelated information into a well organized and easy to read file. Today we’ll be looking at how to take advantage of this with Flex 3. This tutorial will teach how to load an external XML file into Flex and then filter the results into labels.

Set Up the Workspace

Open up the Flex 3 Builder and start a new MXML application. I have named mine xmlSandbox for this example. Set the layout to vertical and press finish.

New MXML Application - xmlsandbox

Before we can load an XML file we’ll need to have one. I’ve made one for this tutorial which you can download. Make a new folder within your ‘src’ folder by right clicking the icon and selecting New>Folder. Name this new folder “assets” and import the downloaded XML file into it. Once you’ve done that, we’re ready to link to it in the Flex document.

Load the XML

MXML makes loading external files easy with the HTTPService tag. Write the following code immediately under the opening application tag.

<mx:HTTPService url="assets/content.xml" id="siteData" resultFormat="e4x"/>

You just created an HTTP Service with an id of ‘siteData’ which links to the XML file in the assets folder. The results are formatted in e4x, which allows us to filter through the contents of the XML file. In order for this url to be loaded, we must tell the application to send the request. We do this by adding the event ‘creationComplete’ to the opening application tag.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="siteData.send()">

The creationComplete event is called when the page loads. In the above code we are saying then when the page is finished loading, the HTTPService named ‘siteData’ should be sent. Take a moment to test your application. It should run without errors if the XML is being loaded correctly.


Filter XML Data

The XML data will need a place to store itself while we work with it. Make a script tag immediately below the opening application tag and declare the following variable.

<mx:Script>
        <![CDATA[
                private var siteContent:XMLList;
]]>
</mx:Script>

The XMLList type allows us to load XML data in and work with it. To demonstrate this we’re going to build a function that will load data from the XML file and display it in labels. Add the following function to your script tag.

private function showPage(targetPage:String):void{
                //Search for title of target page
                siteContent = siteData.lastResult.page.(@location==targetPage).title;
                //Show result in label
                headerText.text=siteContent;

                //Search for body text of target page
                siteContent = siteData.lastResult.page.(@location==targetPage).text;
                //Show result in label
                bodyText.text=siteContent;
            }

Now below the HTTPService tag we’re going to insert some components for the results to load into. We are also adding buttons to control navigation.

<mx:VBox>
        <mx:Label fontSize="24" id="headerText" text="Click a Button"/>
        <mx:Label id="bodyText" text="The choice is yours!"/>

        <mx:HBox>
            <mx:Button label="Home Page" click="showPage('home')"/>
            <mx:Button label="About Page" click="showPage('about')"/>
            <mx:Button label="Contact Page" click="showPage('contact')"/>
        </mx:HBox>
    </mx:VBox>

So what exactly did we just do? Here’s an overview of what is happening:

  1. When one of the buttons is pressed it passes a string to the showPage function.
  2. showPage receives this parameter as a string called targetPage.
  3. This targetPage will determine which XML node is to be displayed.
  4. Each node of the XML file has an attribute called “location” which corresponds to the passed value of targetPage.
  5. The siteContent XMLList matches a node to the targetPage and then loads the correct title and body text into their respective labels.

Conclusion

There you have it! Run your application. If everything is working as it should, the data from the XML file is loaded up for each page when a button is pressed. Not bad! You aren’t limited to just text. Try loading the url of an image from an XML file with Flex. XML has a wide number of possibilities to explore.

XML Basics in Flex

View the live demo

Download the source files

Wordpress.com stats not installed! Posted Wednesday, December 10th, 2008 / Back to Top

I this post. Tweet
SPONSOR

21 Comments 9 Mentions

  1. lopsact Author Editor

    ThanQ for giving such guidence………cheers !

    January 9, 2009 · Reply

  2. Avron Author Editor

    Zach,
    New to Flex downloaded the source compiled ok but buttons do not change the content. Have checked the file structure etc…
    Any ideas ?

    February 3, 2009 · Reply

  3. Avron Author Editor

    Zach,

    Problem resolved ! Was not running Webserver. Thanks for the great posting !

    February 3, 2009 · Reply

  4. Zach Dunn Author Editor

    Avron,

    Sorry to hear you’re having problems! Let’s get you straightened out! Have you tried uploading your compiled files to a server?

    From experience, I can tell you that Flex and Flash have very specific rules with HTTP requests on files locally. Generally if you try to open a page that requests external files through HTTP requests on your local machine, it will not work. It’s a nuisance, and I know that the Flex Builder can compensate for it. I cannot speak for the SDK, but I would assume the same

    This would be my guess at the problem. Upload the related files to a server and see if they load properly. Let me know if that fixes anything for you.

    February 3, 2009 · Reply

  5. Avron Author Editor

    Hi Zach, thanks you were right of course. Seems as if a “file” is not a URL to flex.

    One further interest, I would like to load html, can you describe a way in which I may do that ?

    I have changed the label to
    and in the function showPage(), have … bodyText.htmlText=siteContent;
    it seems as if each new (xml complient) tag is output on a newline

    -
    -
    New Home Page
    -
    -
    Here is a whole lot of text that should go in here and then I am going to put in a
    bold
    tag

    -
    About Page
    More about this site.

    -
    Contact Us
    Get in touch!

    outputs :

    Here is a whole lot of text that should go in here and then I am going to put in a
    bold
    tag

    Since I am really hacking here, any help will be appreciated ;-)

    February 3, 2009 · Reply

  6. Marsha Author Editor

    Thanks for a tutorial/example that actually works and explains what is going on. I’ve tried a bunch of tutorials from the Adobe site that won’t compile. This was just what I needed. Thanks again and keep up the good work!

    March 10, 2009 · Reply

  7. Shaun Author Editor

    Thanks for this mate, exactly what I was looking for!

    March 26, 2009 · Reply

  8. Alvi Author Editor

    This is very nice but if you write the code for the image show from xml.
    it is more best.

    April 6, 2009 · Reply

  9. Luis Gomez Author Editor

    Gracias por el tutorial , es lo que estaba buscando

    April 29, 2009 · Reply

  10. sana Author Editor

    Hi, i am new to flex and have taken a few classes on it but still i’m unable to read two(2) xml files into the external script and hence, the data is not displayed while running the mxml application. can anyone sort what the problem is, though i have used the same procedure for reading a single xml file into mxml?

    July 15, 2009 · Reply

  11. Manoj Kumar Sharma Author Editor

    HI, Please visit to read news

    November 19, 2009 · Reply

  12. Manoj Kumar Sharma Author Editor

    Thanks It’s Greate Tutorial.

    November 19, 2009 · Reply

  13. XManHere Author Editor

    thnx 4 the tutorial and discussion…
    i faced the problem of running the app on local machine bt now i kno what to do… :)

    November 22, 2009 · Reply

  14. cnrdzn Author Editor

    @Zach Dunn

    Thanks ;)

    @Avron
    find
    bodyText.text=siteContent;

    change
    bodyText.htmlText=siteContent;

    open xml data and change text tag
    <![CDATA[
    Adobe Flex,test,font, orhtml
    ]]>

    demo: http://cnr.gen.tr/flex/

    January 14, 2010 · Reply

  15. cnrdzn Author Editor

    text tag

    <![CDATA[
    Adobe Flex,test,font, orhtml
    ]]>

    January 14, 2010 · Reply

  16. Tahir Alvi Author Editor

    Nice post.

    Thanks

    November 27, 2010 · Reply

  17. Abhisek Author Editor

    Hi Zach,

    Very new to flex and have to develop “Box and Whisker Chart” in flex. Can you please help me in this regards or suggest any tutorial which can help me.

    Thanks in advance :)

    March 22, 2011 · Reply

  18. Condeccia Author Editor

    Great tutorial and just what I was looking for.
    Can you tell me what i would need to add to the code to upload an image? I have amended the xml but i can’t get the image to display? Thank you.

    May 4, 2011 · Reply

  19. Radosveta Author Editor

    Hey, thanks for the great tutorial! But, I am stuck on the loading part… I get the following error “XML document structures must start and end within the same entity.” I checked and my xml files validate but because I still got this error I tried using your sample file and it still won’t work. I even changed workspaces in case some files from other projects I have tried are left. Or am I importing the file the wrong way? I go Import>General>FIle System. Any ideas?

    July 23, 2011 · Reply

  20. Radosveta Author Editor

    Oh, please never mind me! I sould have read more carefully we add something to the Application tag and it’s not a new tag we insert. Now I feel like a dunce :/

    July 24, 2011 · Reply

 

Join the Conversation

Back to Top / Comment RSS

2012 Build Internet. Created by One Mighty Roar. Icons by Komodo Media. Back to Top