Milad
Milad

Reputation: 1269

Adobe Air as3 - Read XML file from desktop

How can I read an xml file located on user's desktop? I've tried this:

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

var myXML:XML = new XML();
var myLoader:URLLoader = new URLLoader(new URLRequest(File.desktopDirectory.nativePath + "/a.xml"));
myLoader.addEventListener(Event.COMPLETE, xmlLoaded);

function xmlLoaded(event:Event):void
{
    myXML = XML(myLoader.data);
    trace(myXML);       
}

but it doesn't work.

Upvotes: 1

Views: 3101

Answers (3)

aldoyh
aldoyh

Reputation: 63

You would also need to import this:

import flash.net.URLRequest;

Upvotes: 0

ndm
ndm

Reputation: 60463

When using the URLLoader with local files, you should use a proper URL scheme, like file, app or app-storage. The File.url property will give you the appropriate local URL, for example file:///C:/Users/Username/Desktop/.

File.desktopDirectory.resolvePath('a.xml').url

Another, and often better approach is to use the FileStream API, as it's designed for the very purpose of filesystem communication, also it supports synchronous operations:

var file:File = File.desktopDirectory.resolvePath('a.xml');
var document:XML;

var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
document = XML(stream.readUTFBytes(stream.bytesAvailable));
stream.close();

trace(document);

Upvotes: 7

Milad
Milad

Reputation: 1269

apparently, this can be done by simply adding a '/'.

var myLoader:URLLoader = new URLLoader(new URLRequest(File.desktopDirectory.nativePath + "/a.xml"));

change to:

var myLoader:URLLoader = new URLLoader(new URLRequest("/" + File.desktopDirectory.nativePath + "/a.xml"));

Upvotes: 0

Related Questions