简体   繁体   中英

AS3: Parsing XML with a variable command

I'm doing some level load parsing from Ogmo and I ran into a problem. If I have just one layer, I can read it in like this:

private function drawLayer(layer:String,xml:Class):void
    {
        var rawData:ByteArray = new xml;
        var dataString:String = rawData.readUTFBytes(rawData.length);
        var typeString:String = "LevelData." + layer + ".tile";
        trace ("Type STring:" + typeString);
        LevelData = new XML(dataString);

        var dataList:XMLList;
        var dataElement:XML;
        dataList = LevelData.terrain.tile; 
        //trace ("dataList: " + dataList);
        for each(dataElement in dataList)
        {    tIndex = (int(dataElement.@tx) / 32) + ((int(dataElement.@ty) / 32) * 9);
            //trace("tIndex is: " + tIndex); 
            _tiles.setTile(int(dataElement.@x) / 32, int(dataElement.@y / 32), tIndex);
        }

Where LevelData.terrain.tile is the XML parse string. However, I have a few ifferent layers and I wanted to be able to parse dynamically, ie:

dataList = typeString;

But that doesn't work,. but it attempts to parse typeString out of the XML, not the "typeString" string. I can't see a way to do what I'm trying to do, but I figured if anyone knew a way, they'd be on StackOverflow.

Thanks in advance!

You could try:

dataList = LevelData[layer].tile;

Tip: don't use capitalized names for variables; normally those are used with class names. Your code might get confusing if you mix those.

I'm assuming your xml has the following structure:

<level>
    <layer>
        <terrain>
            <tile/>
        </terrain>

        ...

    </layer>
</level>

Based on your method header, I'm presuming you wish to dynamically access either layer 0 tiles, or layer n tiles. You can use E4X in the following manner:

var tiles:XMLList = levelData.layer[index]..tile;

If you have indicies associated with each layer as an attribute:

<layer index="0"/>

The above statement could become:

var tiles:XMLList = levelData.layer.(@index == 0)..tile;

the ".." expression may be replace with the full path to the tile tag.

Senocular has a great E4X page:

http://www.senocular.com/flash/tutorials/as3withflashcs3/?page=4

I'm not too sure if anything in this format

"LevelData."

will work for you in actionscript. Always consider an object as an dictionary where you do .

LevelData["something"] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM