Flex を使用している場合は、SimpleXMLDecoder
function toObj(data:XML):Object {
var xmlDoc:XMLDocument = new XMLDocument(data);
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
return decoder.decodeXML(xmlDoc);
}
function toXML(obj:Object):XML {
var qName:QName = new QName("root");
var xmlDoc:XMLDocument = new XMLDocument();
var simpleXMLEncoder:SimpleXMLEncoder = new SimpleXMLEncoder(xmlDoc);
var xmlNode:XMLNode = simpleXMLEncoder.encodeValue(obj, qName, xmlDoc);
return new XML(xmlDoc.toString());
}
私のように、Flex とその API を使用していない場合は、私が作成した Object に変換するための純粋な AS3 メソッドを次に示します。これは、オブジェクトへの移動のみをカバーしています。文字列にシリアル化する必要はありません。
function translateXML(xml:XML):* {
/* Created by Atriace: Converts XML into an Object, with nested arrays, and relevant object types.
Useful if you find AS3's XML methods an asinine waste of time. */
var data:XMLList = xml.children();
var store:Object = mineAttributes(xml.attributes()), item, key:String;
if (hasTwo(data)) { // should this be an object or array?
for each (item in data) { // we store arrays by the name of the array
key = item.name();
if (store[key] == null) {
store[key] = new Array(); // and then the contents inside that array
} else if (getType(store[key]) != "Array") {
trace("store[" + key + "] = " + store[key] + ":" + getType(store[key]));
}
store[key].push(translateXML(item));
}
} else { // Assuming there were no repeating elements at the beginning, we create unique objects
for each (item in data){
key = item.name();
if (key == null) { // Assuming we have an encapsulated string, we add a tag called "content" with its value.
store["content"] = item.toString();
} else {
store[key] = translateXML(item); // Otherwise, we recursively loop into the nested objects.
}
}
}
return store;
}
function hasTwo(data):Boolean {
/* Determines whether there are two of the same object name at the beginning of a list. */
var answer:Boolean = false;
var original;
var i:int = 1;
for each (var k in data) {
if (i == 2) {
if (original == k.name()) {
answer = true;
}
break;
} else {
original = k.name();
}
i++
}
return answer;
}
function mineAttributes(data:XMLList):* {
/* Returns all the attibutes of an XML node */
var d:Object = {}, key:String, val:String;
for each (var item in data){
key = item.name();
val = item;
d[key] = val;
}
return d;
}
function getType(value:*):String {
// Returns the type of object passed to it.
var msg:String = flash.utils.getQualifiedClassName(value);
if (msg.lastIndexOf("::") != -1) {msg = msg.split("::")[1];}
return msg;
}