Turn an XML string into an Object in Actionscript

我只是一个虾纸丫 提交于 2019-12-25 07:50:03

问题


I am pretty new to AS, and I am assuming there is a way to do this and I am just not figuring it out. Basically, I am trying to use a service that returns xml and return an Object regardless of the structure of the xml. In .Net I use the XmlSerializer.Deserialize class... is there equivalent in AS?

I was able to find SimpleXMLDecoder but I can't seem to get it to work - it also looks like it might only work with nodes? Either way, the examples out there are sparse and hard to follow, I just want to know how to take xml like this:

<?xml version=\"1.0\" encoding=\"utf-8\"?>
<Company>
    <Id>2</Id>
    <Name>Stan</Name>
    <Size>10</Size>
</Company>; 

And simply turn it into an Object - is this possible without writing my own parser? Thank you.


回答1:


You can use the HTTPService

There's a good example here...

  • http://blog.flexexamples.com/2007/07/27/loading-xml-at-run-time-using-the-mxhttpservice-tag/
  • and here http://colourgray.wordpress.com/2008/08/08/flex-processing-xml-response-from-httpservice/

Basically it will serialize the result into an object from XML when you retrieve it.




回答2:


ActionScript has its own XML parser then you don't need to write yours.

XML from a String

If you have a String to convert, you can just convert it as XML inline with few lines of code like this:


import flash.xml.*;

var xml : XML = XML( '<?xml version="1.0" encoding="utf-8"?><Company><Id>2</Id><Name>Stan</Name><Size>10</Size></Company>' );

trace( 'Id:' + xml.Id ); // Should trace "2"
trace( 'Name:' + xml.Name ); // Should trace "Stan"

XML from an external file

Otherwise you can just load it in runtime in this way:


import flash.net.*;
import flash.events.*;
import flash.xml.*;

var xmlLoader : URLLoader = new URLLoader();
xmlLoader.addEventListener( Event.COMPLETE, doStuffWithLoadedXML );

function doStuffWithLoadedXML( e : Event ) : void 
{                             
    var xml : XML = new XML( e.target.data );
    trace( 'Id:' + xml.Id ); // Should trace "2"
    trace( 'Name:' + xml.Name ); // Should trace "Stan"
}

xmlLoader.load( new URLRequest( 'yourfile.xml' ) );

Edited with links

Some nice links to start working:

The Basic
http://blog.theflashblog.com/?p=242

Some nice E4X tips and how-to
http://www.senocular.com/flash/tutorials/as3withflashcs3/?page=4

Hope this helps. Ciao!



来源:https://stackoverflow.com/questions/4929193/turn-an-xml-string-into-an-object-in-actionscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!