1

I'm trying to load an XML file with a list of books, I looked around and found this function, tried to adjust it to work for me, but I cant get this to work, I'm able to load the XML and actually read the info from it, but I was trying to set a global array or something like that so I can access the data later,

heres the code:

var books:XML = loadBooks();
trace(books); //Returns a blank output

function loadBooks():XML {
    var xmlLoader:URLLoader = new URLLoader();
    var xmlData:XML = new XML();
    xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
    xmlLoader.load(new URLRequest("bookList.xml"));

    function LoadXML(e:Event):void {
    xmlData = new XML(e.target.data);
    trace(xmlData); //Returns what I want to have
    }

    return xmlData;
}

I added comments on the trace() parts to explain a little about what's happening Thanks in advance.

1
  • 1
    the issue is you xml loads asynchronously: your LoadXML() function gets called independently of loadBooks(), so you may call loadBooks() at time A, but more than likely loadXML() will be called a different time B. You should change your code to cater for that. Commented Apr 2, 2012 at 12:43

2 Answers 2

1

The first trace does not show what you want, because the XML is loaded asynchronously. This is why you add the LoadXML as an event listener for the "complete" event. So, whatever you want to do with the loaded XML, you should do it in the LoadXML function.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, it works now and I now understand what the problem was
0

At the initial stage you're trying to trace books, the loader hasn't finished loading in your XML file - so it will not trace anything. The second one however will because it is tied to the Complete event and will only be fired when the loader has finished loading the XML. So as above, anything you want to do with your XML file should be placed inside the LoadXML function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.