Michael Blatz
Michael Blatz

Reputation: 63

Import xml into a xml and read it with actionscript 3

I want to import a xml into an xml and read it with ActionScript 3. A single imported xml-File is possible to import but I have a big problem using it that way I want to.

So my first xml-File looks that way:

<!DOCTYPE doc [
<!ENTITY bonuses SYSTEM "bonuses.xml">
]>    
<mission>
            ...
            <wealth money="1000" />
            <bonuses>bonus</bonuses>
            <bonuses>
                <first>&bonuses;</first>
                <second>&bonuses;</second>
            </bonuses>
        </mission>

My Second file looks that way:

<?xml version="1.0" encoding="utf-8"?>
<bananas>
    <descr>Banana Description</descr>
    <impact>You gain more gold!</impact>
    <bonus>15</bonus>
</bananas>

I'm trying to access the xml file with this function:

private function xmlLoaded(e:Event):void 
{
    _xml = new XML(e.target.data);
    trace("XML LOADER: XML LOADED CORRECTLY");
// Correct Output: Bonus
        trace("XML LOADER: BONUS 0: " + _xml.mission[0].bonuses[0]); 
// Incorrect Output: Nothing!
    trace("XML LOADER: BONUS 1: " + _xml.mission[0].bonuses[1].first.descr);
    _stage.dispatchEvent(new Event("completed"));
}

Like I said this works fine for the first loaded xml file but not for the imported. Are there any soultions or is it a restriction of actionscript?

Thanks a lot!

Greetings Michael

Upvotes: 0

Views: 108

Answers (2)

Pier
Pier

Reputation: 10817

Well, there are many bizarre things in your code.

1) Are you loading both XMLs into the same object _xml? You should have a different object for each XML. When you do the following code, you are removing what's inside _xml and putting something new.

_xml = new XML(e.target.data);

2) Of course your second trace will never work, even if you had 2 XML objects, because it's not using the nodes correctly... it should be simply this.

trace(_xml.descr);

If you need to combine the 2 XMLs into one XMl object, you need to do that after loading both XMLs.

Upvotes: 0

Discipol
Discipol

Reputation: 3157

First of all, don't use XML, use JSON. Actionscript 3 has a native JSON parser, which is faster than the default XML parser. JSON supports arrays, it's easier to read and 50% to 66% in size of the same data in XML. Actionscript 3 converts a JSON string into an Object with properties which eliminates the need of stuff like _xml.mission[0].bonuses[1].first.descr.

Once you switch to JSON, problems like yours just fly away on the back of butterflies twinkle, twinkle.

If you DO have to use an XML, then get yourself or make yourself an XML to Object converter, which is something you can easily debug. Convert attributes to properties, child nodes into an array with said children, etc.

Upvotes: 1

Related Questions