开发者

Flash - XML random text display

I am stumped on this... All I want is to display a ra开发者_如何学运维ndom node from an xml file in Flash... I can display one node fine, but if try to display 2 or more, Flash sticks the XML tags back on the items - change the number following questions in the urlLoader_complete function to see what I mean. Here's my AS3:

var questions:XML;

var urlRequest:URLRequest = new URLRequest("breakfast.xml");
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
urlLoader.load(urlRequest);

function urlLoader_complete(evt:Event):void {
    questions = new XML(evt.target.data);
    textArea.text = generateRandomQuestions(questions, 2).toString();
}

function generateRandomQuestions(source:XML, nodes:int = 6):XMLList
{
    if (source.*.length() < nodes) return source.*;
    var list:XMLList;
    var hash:Array = [];
    var randomPosition:int;
    var node:XML;
    do
    {
        node = source.*[(Math.random() * source.*.length()) >> 0];
        if (hash.indexOf(node.toXMLString()) < 0)
        {
            hash.push(node.toXMLString());
            list ? list += node : list = XMLList(node);
        }
    } while (list.length() < nodes)
    return list;
}

and my XML:

<?xml version="1.0" encoding="utf-8"?>
<breakfast>
    <person>K</person>
    <person>Dave</person>
    <person>Andrew</person>
    <person>Bart</person>
    <person>Ricky</person>
</breakfast>


Try this out.

import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;

var urlRequest:URLRequest = new URLRequest("test.xml");
var urlLoader:URLLoader = new URLLoader();
urlLoader.load(urlRequest);
urlLoader.addEventListener(Event.COMPLETE, loadComplete, false, 0, true);

function loadComplete(evt:Event):void
{
    var xml:XML = new XML(evt.target.data);
    trace(generateRandomNodes(xml, 3).toString());
}

function generateRandomNodes(xml:XML, limit:int):Array
{
    var nodes:Array = new Array();
    for each(var node in xml.children())
    {
        nodes.push(node);
    }
    if(limit <= nodes.length)
    {
        nodes = shuffleArray(nodes);
        return nodes.slice(0, limit);
    }else
    {
        return [];
    }
}

function shuffleArray(array:Array):Array
{
    var temp:Array = new Array();
    for(var i:int=0;i<array.length;i++) 
    {
        var rand = Math.floor(Math.random() * (i + 1));
        var tmp = array[i];
        temp[i] = temp[rand];
        temp[rand] = tmp;
    }
    return temp;
}

This will give you an array with randomly shuffled XML node values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜