我对此感到难过......我只想在Flash中的xml文件中显示一个随机节点... 我可以很好地显示一个节点,但如果尝试显示2个或更多节点,Flash会将XML标签粘贴回项目 - 更改urlLoader_complete函数中的问题后面的数字以查看我的意思。 这是我的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;
}
和我的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>
答案 0 :(得分:1)
试试这个。
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;
}
这将为您提供一个包含随机混乱的XML节点值的数组。