Top Level

Class XML

Object


public class XML
extends XMLNode

Player version: Flash Player 5 — (became a native object in Flash Player 6, which improved performance significantly).

Use the methods and properties of the XML class to load, parse, send, build, and manipulate XML document trees.

You must use the constructor new XML() to create an XML object before calling any method of the XML class.

An XML document is represented in Flash by the XML class. Each element of the hierarchical document is represented by an XMLNode object.

For information on the following methods and properties, you can see the XMLNode class, specifically appendChild(), attributes, childNodes, cloneNode(), firstChild, hasChildNodes(), insertBefore(), lastChild, nextSibling, nodeName, nodeType, nodeValue, parentNode, previousSibling, removeNode(), and toString().

In earlier versions of the ActionScript Language Reference, the previous methods and properties were documented in the XML class. They are now documented in the XMLNode class.

Note: The XML and XMLNode objects are modeled after the W3C DOM Level 1 recommendation, which you can find at: http://www.w3.org/tr/1998/REC-DOM-Level-1-19981001/level-one-core.html. That recommendation specifies a Node interface and a Document interface. The Document interface inherits from the Node interface, and adds methods such as createElement() and createTextNode(). In ActionScript, the XML and XMLNode objects are designed to divide functionality along similar lines.

See also
XMLNode.appendChild(), XMLNode.attributes, XMLNode.childNodes, XMLNode.cloneNode(), XMLNode.firstChild, XMLNode.hasChildNodes(), XMLNode.insertBefore(), XMLNode.lastChild, XMLNode.nextSibling, XMLNode.nodeName, XMLNode.nodeType, XMLNode.nodeValue, XMLNode.parentNode, XMLNode.previousSibling, XMLNode.removeNode(), XMLNode.toString()



Property Summary
contentType : String
The MIME content type that is sent to the server when you call the XML.send() or XML.sendAndLoad() method.
docTypeDecl : String
Specifies information about the XML document's DOCTYPE declaration.
idMap : Object
An object containing the XML file's nodes that have an id attribute assigned.
ignoreWhite : Boolean
Default setting is false.
loaded : Boolean
The property that indicates whether the XML document has successfully loaded.
status : Number
Automatically sets and returns a numeric value that indicates whether an XML document was successfully parsed into an XML object.
xmlDecl : String
A string that specifies information about a document's XML declaration.

Properties inherited from class XMLNode
attributes, childNodes, firstChild, lastChild, localName, namespaceURI, nextSibling, nodeName, nodeType, nodeValue, parentNode, prefix, previousSibling

Properties inherited from class Object
__proto__, __resolve, constructor, prototype


Event Summary
onData = function(src:String) {}
Invoked when XML text has been completely downloaded from the server, or when an error occurs downloading XML text from a server.
onHTTPStatus = function(httpStatus:Number) {}
Invoked when Flash Player receives an HTTP status code from the server.
onLoad = function(success:Boolean) {}
Invoked by Flash Player when an XML document is received from the server.


Constructor Summary
XML(text:String)
Creates a new XML object.


Method Summary
addRequestHeader(header:Object, headerValue:String) : Void
Adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions.
createElement(name:String) : XMLNode
Creates a new XML element with the name specified in the parameter.
createTextNode(value:String) : XMLNode
Creates a new XML text node with the specified text.
getBytesLoaded() : Number
Returns the number of bytes loaded (streamed) for the XML document.
getBytesTotal() : Number
Returns the size, in bytes, of the XML document.
load(url:String) : Boolean
Loads an XML document from the specified URL, and replaces the contents of the specified XML object with the downloaded XML data.
parseXML(value:String) : Void
Parses the XML text specified in the value parameter, and populates the specified XML object with the resulting XML tree.
send(url:String, [target:String], [method:String]) : Boolean
Encodes the specified XML object into an XML document and sends it to the specified target URL.
sendAndLoad(url:String, resultXML:XML) : Void
Encodes the specified XML object into an XML document, sends it to the specified URL using the POST method, downloads the server's response, and loads it into the resultXMLobject specified in the parameters.

Methods inherited from class XMLNode
appendChild, cloneNode, getNamespaceForPrefix, getPrefixForNamespace, hasChildNodes, insertBefore, removeNode, toString

Methods inherited from class Object
addProperty, hasOwnProperty, isPropertyEnumerable, isPrototypeOf, registerClass, toString, unwatch, valueOf, watch


Property Detail

contentType Property

public contentType : String

Player version: Flash Player 6

The MIME content type that is sent to the server when you call the XML.send() or XML.sendAndLoad() method. The default is application/x-www-form-urlencoded, which is the standard MIME content type used for most HTML forms.

Example
The following example creates a new XML document and checks its default content type:
// create a new XML document
var doc:XML = new XML();

// trace the default content type
trace(doc.contentType);  // output: application/x-www-form-urlencoded

The following example defines an XML packet, and sets the content type for the XML object. The data is then sent to a server and shows a result in a browser window.

var my_xml:XML = new XML("<highscore><name>Ernie</name><score>13045</score></highscore>");
my_xml.contentType = "text/xml";
my_xml.send("http://www.flash-mx.com/mm/highscore.cfm", "_blank");

Press F12 to test this example in a browser.

See also
XML.send(), XML.sendAndLoad()

docTypeDecl Property

public docTypeDecl : String

Player version: Flash Player 5

Specifies information about the XML document's DOCTYPE declaration. After the XML text has been parsed into an XML object, the XML.docTypeDecl property of the XML object is set to the text of the XML document's DOCTYPE declaration (for example, <!DOCTYPE greeting SYSTEM "hello.dtd">). This property is set using a string representation of the DOCTYPE declaration, not an XML node object.

The ActionScript XML parser is not a validating parser. The DOCTYPE declaration is read by the parser and stored in the XML.docTypeDecl property, but no Dtd validation is performed.

If no DOCTYPE declaration was encountered during a parse operation, the XML.docTypeDecl property is set to undefined. The XML.toString() method outputs the contents of XML.docTypeDecl immediately after the XML declaration stored in XML.xmlDecl, and before any other text in the XML object. If XML.docTypeDecl is undefined, no DOCTYPE declaration is output.

Example
The following example uses the XML.docTypeDecl property to set the DOCTYPE declaration for an XML object:
my_xml.docTypeDecl = "<!DOCTYPE greeting SYSTEM \"hello.dtd\">";

See also
XML.xmlDecl

idMap Property

public idMap : Object

Player version: Flash Player 8

An object containing the XML file's nodes that have an id attribute assigned. The names of the properties of the object (each containing a node) match the values of the id attributes.

Consider the following XML object:


      <employee id='41'>
          <name>
              John Doe
          </name>
          <address>
              601 Townsend St.
          </address>
      </employee>
      
      <employee id='42'>
          <name>
              Jane Q. Public
          </name>
      </employee>
      <department id="IT">
          Information Technology
      </department>
      

In this example, the idMap property for this XML object is an Object with three properties: 41, 42, and IT. Each of these properties is an XMLNode that has the matching id value. For example, the IT property of the idMap object is this node:


      <department id="IT">
          Information Technology
      </department>
      

You must use the parseXML() method on the XML object for the idMap property to be instantiated.

If there is more than one XMLNode with the same id value, the matching property of the idNode object is that of the last node parsed, as follows:

var x1:XML = new XML("<a id='1'><b id='2' /><c id='1' /></a>");
x2 = new XML();
x2.parseXML(x1);
trace (x2.idMap['1']);

The following will output the <c> node:

      <c id='1' />
      

Example
You can create a text file named idMapTest.xml that contains the following text.

      <?xml version="1.0"?> 
      <doc xml:base="http://example.org/today/" xmlns:xlink="http://www.w3.org/1999/xlink"> 
        <head> 
          <title>Virtual Library</title> 
        </head> 
        <body> 
          <paragraph id="linkP1">See <link xlink:type="simple" xlink:href="new.xml">what's 
            new</link>!</paragraph> 
          <paragraph>Check out the hot picks of the day!</paragraph> 
          <olist xml:base="/hotpicks/"> 
            <item> 
              <link id="foo" xlink:type="simple" xlink:href="pick1.xml">Hot Pick #1</link> 
            </item> 
            <item> 
              <link id="bar" xlink:type="simple" xlink:href="pick2.xml">Hot Pick #2</link> 
            </item> 
            <item> 
              <link xlink:type="simple" xlink:href="pick3.xml">Hot Pick #3</link> 
            </item> 
          </olist>
        </body> 
       </doc>
      

Then you can create a SWF file in the same directory as the XML file. You can include the following script in the SWF.

var readXML = new XML();
readXML.load("idMapTest.xml");
readXML.onLoad = function(success) {
    myXML = new XML();
    myXML.parseXML(readXML);    
    for (var x in myXML.idMap){
        trace('idMap.' + x + " = " + newline + myXML.idMap[x]);
        trace('____________' + newline);
    }
}

When you test the SWF file, the following output is generated.


      idMap.bar = 
      <link id="bar" xlink:type="simple" xlink:href="pick2.xml">Hot Pick #2</link>
      ____________
      
      idMap.foo = 
      <link id="foo" xlink:type="simple" xlink:href="pick1.xml">Hot Pick #1</link>
      ____________
      
      idMap.linkP1 = 
      <paragraph id="linkP1">See <link xlink:type="simple" xlink:href="new.xml">what's 
      
            new</link>!</paragraph>
      ____________
      


ignoreWhite Property

public ignoreWhite : Boolean

Player version: Flash Player 5

Default setting is false. When set to true, text nodes that contain only white space are discarded during the parsing process. Text nodes with leading or trailing white space are unaffected.

Usage 1: You can set the ignoreWhite property for individual XML objects, as the following code shows:

my_xml.ignoreWhite = true;

Usage 2: You can set the default ignoreWhite property for XML objects, as the following code shows:

XML.prototype.ignoreWhite = true;

Example
The following example loads an XML file with a text node that contains only white space; the foyer tag comprises fourteen space characters. To run this example, create a text file named flooring.xml, and copy the following tags into it:

      <house>
         <kitchen>   ceramic tile   </kitchen>
         <bathroom>linoleum</bathroom>
         <foyer>              </foyer>
      </house>
      

Create a new Flash document named flooring.fla and save it to the same directory as the XML file. Place the following code into the main Timeline:

// Create a new XML object.
var flooring:XML = new XML();

// Set the ignoreWhite property to true (default value is false)
flooring.ignoreWhite = true;

// After loading is complete, trace the XML object.
flooring.onLoad = function(success:Boolean) {
    trace(flooring);
}

// Load the XML into the flooring object.
flooring.load("flooring.xml");

// Output (line breaks added for clarity):
<house>
    <kitchen>   ceramic tile   </kitchen>
    <bathroom>linoleum</bathroom>
    <foyer />
</house>

If you then change the setting of flooring.ignoreWhite to false, or simply remove that line of code entirely, the fourteen space characters in the foyer tag will be preserved:

...
// Set the ignoreWhite property to false (default value).
flooring.ignoreWhite = false;
...
// Output (line breaks added for clarity):
<house>
    <kitchen>   ceramic tile   </kitchen>
    <bathroom>linoleum</bathroom>
    <foyer>              </foyer>
</house>

The XML_blogTracker.fla and XML_languagePicker.fla files in the ActionScript samples folder also contain a code example. The following are typical paths to this folder:


loaded Property

public loaded : Boolean

Player version: Flash Player 5

The property that indicates whether the XML document has successfully loaded. If there is no custom onLoad() event handler defined for the XML object, Flash Player sets this property to true when the document-loading process initiated by the XML.load() call has completed successfully; otherwise, it is false. However, if you define a custom behavior for the onLoad() event handler for the XML object, you must be sure to set onload in that function.

Example
The following example uses the XML.loaded property in a simple script.
var my_xml:XML = new XML();
my_xml.ignoreWhite = true;
my_xml.onLoad = function(success:Boolean) {
    trace("success: "+success);
    trace("loaded:  "+my_xml.loaded);
    trace("status:  "+my_xml.status);
};
my_xml.load("http://www.flash-mx.com/mm/problems/products.xml");

Information is displayed in the Output panel when Flash invokes the onLoad() handler. If the call completes successfully, true is displayed for the loaded status in the Output panel.

Information writes to the log file when the onLoad handler invokes. If the call completes successfully, true is written to the log file for the loaded status.


      success: true
      loaded:  true
      status:  0
      

See also
XML.load(), XML.onLoad

status Property

public status : Number

Player version: Flash Player 5

Automatically sets and returns a numeric value that indicates whether an XML document was successfully parsed into an XML object. The following are the numeric status codes, with descriptions:

Example
The following example loads an XML packet into a SWF file. A status message displays, depending on whether the XML loads and parses successfully. Add the following ActionScript to your FLA or AS file:
var my_xml:XML = new XML();
my_xml.onLoad = function(success:Boolean) {
    if (success) {
    if (my_xml.status == 0) {
        trace("XML was loaded and parsed successfully");
    } else {
        trace("XML was loaded successfully, but was unable to be parsed.");
    }
    var errorMessage:String;
    switch (my_xml.status) {
    case 0 :
        errorMessage = "No error; parse was completed successfully.";
        break;
    case -2 :
        errorMessage = "A CDATA section was not properly terminated.";
        break;
    case -3 :
        errorMessage = "The XML declaration was not properly terminated.";
        break;
    case -4 :
        errorMessage = "The DOCTYPE declaration was not properly terminated.";
        break;
    case -5 :
        errorMessage = "A comment was not properly terminated.";
        break;
    case -6 :
        errorMessage = "An XML element was malformed.";
        break;
    case -7 :
        errorMessage = "Out of memory.";
        break;
    case -8 :
        errorMessage = "An attribute value was not properly terminated.";
        break;
    case -9 :
        errorMessage = "A start-tag was not matched with an end-tag.";
        break;
    case -10 :
        errorMessage = "An end-tag was encountered without a matching
        start-tag.";
        break;
    default :
        errorMessage = "An unknown error has occurred.";
        break;
    }
    trace("status: "+my_xml.status+" ("+errorMessage+")");
    } else {
    trace("Unable to load/parse XML. (status: "+my_xml.status+")");
    }
};
my_xml.load("http://www.helpexamples.com/flash/badxml.xml");


xmlDecl Property

public xmlDecl : String

Player version: Flash Player 5

A string that specifies information about a document's XML declaration. After the XML document is parsed into an XML object, this property is set to the text of the document's XML declaration. This property is set using a string representation of the XML declaration, not an XML node object. If no XML declaration is encountered during a parse operation, the property is set to undefined. The XML.toString() method outputs the contents of the XML.xmlDecl property before any other text in the XML object. If the XML.xmlDecl property contains the undefined type, no XML declaration is output.

Example
The following example creates a text field called my_txt that has the same dimensions as the Stage. The text field displays properties of the XML packet that loads into the SWF file. The doc type declaration displays in my_txt. Add the following ActionScript to your FLA or AS file:
var my_fmt:TextFormat = new TextFormat();
my_fmt.font = "_typewriter";
my_fmt.size = 12;
my_fmt.leftMargin = 10;

this.createTextField("my_txt", this.getNextHighestDepth(), 0, 0, Stage.width, Stage.height);
my_txt.border = true;
my_txt.multiline = true;
my_txt.wordWrap = true;
my_txt.setNewTextFormat(my_fmt);

var my_xml:XML = new XML();
my_xml.ignoreWhite = true;
my_xml.onLoad = function(success:Boolean) {
    var endTime:Number = getTimer();
    var elapsedTime:Number = endTime-startTime;
    if (success) {
        my_txt.text = "xmlDecl:"+newline+my_xml.xmlDecl+newline+newline;
        my_txt.text += "contentType:"+newline+my_xml.contentType+newline+newline;
        my_txt.text += "docTypeDecl:"+newline+my_xml.docTypeDecl+newline+newline;
        my_txt.text += "packet:"+newline+my_xml.toString()+newline+newline;
    } else {
        my_txt.text = "Unable to load remote XML."+newline+newline;
    }
    my_txt.text += "loaded in: "+elapsedTime+" ms.";
};
my_xml.load("http://www.helpexamples.com/crossdomain.xml");
var startTime:Number = getTimer();

The MovieClip.getNextHighestDepth() method used in this example requires Flash Player 7 or later. If your SWF file includes a version 2 component, use the version 2 components DepthManager class instead of the MovieClip.getNextHighestDepth() method.

See also
XML.docTypeDecl


Event Detail

onData Event Handler

public onData = function(src:String) {}

Player version: Flash Player 5

Invoked when XML text has been completely downloaded from the server, or when an error occurs downloading XML text from a server. This handler is invoked before the XML is parsed, and you can use it to call a custom parsing routine instead of using the Flash XML parser. The src parameter is a string that contains XML text downloaded from the server, unless an error occurs during the download, in which case the src parameter is undefined.

By default, the XML.onData event handler invokes XML.onLoad. You can override the XML.onData event handler with custom behavior, but XML.onLoad is not called unless you call it in your implementation of XML.onData.

Parameters
src:String — A string or undefined; the raw data, usually in XML format, that is sent by the server.

Example
The following example shows what the XML.onData event handler looks like by default:
XML.prototype.onData = function (src:String) {
    if (src == undefined) {
        this.onLoad(false);
    } else {
        this.parseXML(src);
        this.loaded = true;
        this.onLoad(true);
    }
}

You can override the XML.onData event handler to intercept the XML text without parsing it.

See also
XML.onLoad

onHTTPStatus Event Handler

public onHTTPStatus = function(httpStatus:Number) {}

Player version: Flash Player 8

Invoked when Flash Player receives an HTTP status code from the server. This handler lets you capture and act on HTTP status codes.

The onHTTPStatus handler is invoked before onData, which triggers calls to onLoad with a value of undefined if the load fails. It's important to note that after onHTTPStatus is triggered, onData is always subsequently triggered, regardless of whether or not you override onHTTPStatus. To best use the onHTTPStatus handler, write an appropriate function to catch the result of the onHTTPStatus call; you can then use the result in your onData or onLoad handler functions. If onHTTPStatus is not invoked, this indicates that the player did not try to make the URL request. This can happen because the request violates security sandbox rules for the SWF.

If Flash Player cannot get a status code from the server or if Flash Player cannot communicate with the server, the default value of 0 is passed to your ActionScript code. A value of 0 can be generated in any player, such as if a malformed URL is requested, and is always generated by the Flash Player plug-in when run in the following browsers, which do not pass HTTP status codes to the player: Netscape, Mozilla, Safari, Opera, or Internet Explorer for the Macintosh.

Parameters
httpStatus:Number — The HTTP status code returned by the server. For example, a value of 404 indicates that the server has not found anything matching the requested URI. HTTP status codes can be found in sections 10.4 and 10.5 of the HTTP specification at ftp://ftp.isi.edu/in-notes/rfc2616.txt.

Example
The following example shows how to use the onHTTPStatus method to help with debugging. The example collects HTTP status codes and assigns their value and type to an instance of the XML object (notice that this example creates the instance members this.httpStatus and this.httpStatusType at runtime). The onData method uses these to trace information about the HTTP response that could be useful when debugging.
var myXml:XML = new XML();

myXml.onHTTPStatus = function(httpStatus:Number) {
    this.httpStatus = httpStatus;
    if(httpStatus < 100) {
        this.httpStatusType = "flashError";
    }
    else if(httpStatus < 200) {
        this.httpStatusType = "informational";
    }
    else if(httpStatus < 300) {
        this.httpStatusType = "successful";
    }
    else if(httpStatus < 400) {
        this.httpStatusType = "redirection";
    }
    else if(httpStatus < 500) {
        this.httpStatusType = "clientError";
    }
    else if(httpStatus < 600) {
        this.httpStatusType = "serverError";
    }
}

myXml.onData = function(src:String) {
    trace(">> " + this.httpStatusType + ": " + this.httpStatus);
    if(src != undefined) {
        this.parseXML(src);
        this.loaded = true;
        this.onLoad(true);
    }
    else {
        this.onLoad(false);
    }
}

myXml.onLoad = function(success:Boolean) {
}

myXml.load("http://weblogs.macromedia.com/mxna/xml/rss.cfm?query=byMostRecent&languages=1");

See also
LoadVars.onHTTPStatus, XML.load(), XML.sendAndLoad()

onLoad Event Handler

public onLoad = function(success:Boolean) {}

Player version: Flash Player 5

Invoked by Flash Player when an XML document is received from the server. If the XML document is received successfully, the success parameter is true. If the document was not received, or if an error occurred in receiving the response from the server, the success parameter is false. The default, implementation of this method is not active. To override the default implementation, you must assign a function that contains custom actions.

Parameters
success:Boolean — A Boolean value that evaluates to true if the XML object is successfully loaded with a XML.load() or XML.sendAndLoad() operation; otherwise, it is false.

Example
The following example includes ActionScript for a simple e-commerce storefront application. The sendAndLoad() method transmits an XML element that contains the user's name and password, and uses an XML.onLoad handler to process the reply from the server.
var login_str:String = "<login username=\""+username_txt.text+"\" password=\""+password_txt.text+"\" />";
var my_xml:XML = new XML(login_str);
var myLoginReply_xml:XML = new XML();

myLoginReply_xml.ignoreWhite = true;

myLoginReply_xml.onLoad = function(success:Boolean){

    if (success) {

        if ((myLoginReply_xml.firstChild.nodeName == "packet") &&
            (myLoginReply_xml.firstChild.attributes.success == "true")) {
            gotoAndStop("loggedIn");
        } else {
            gotoAndStop("loginFailed");
        }

    } else {
        gotoAndStop("connectionFailed");
    }

};

my_xml.sendAndLoad("http://www.flash-mx.com/mm/login_xml.cfm", myLoginReply_xml);

See also
XML.load(), XML.sendAndLoad(), function statement


Constructor Detail

XML Constructor

public XML(text:String)

Player version: Flash Player 5

Creates a new XML object. You must use the constructor to create an XML object before you call any of the methods of the XML class.

Note: Use the createElement() and createTextNode() methods to add elements and text nodes to an XML document tree.

Parameters
text:String — A string; the XML text parsed to create the new XML object.

Example
The following example creates a new, empty XML object:
var my_xml:XML = new XML();

The following example creates an XML object by parsing the XML text specified in the source parameter, and populates the newly created XML object with the resulting XML document tree:

var other_xml:XML = new XML("<state name=\"California\"><city>San Francisco</city></state>");

See also
XML.createElement(), XML.createTextNode()


Method Detail

addRequestHeader Method

public addRequestHeader(header:Object, headerValue:String) : Void

Player version: Flash Player 6

Adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions. In the first usage, you pass two strings to the method: header and headerValue. In the second usage, you pass an array of strings, alternating header names and header values.

If multiple calls are made to set the same header name, each successive value replaces the value set in the previous call.

You cannot add or change the following standard HTTP headers using this method: Accept-Ranges, Age, Allow, Allowed, Connection, Content-Length, Content-Location, Content-Range, ETag, Host, Last-Modified, Locations, Max-Forwards, Proxy-Authenticate, Proxy-Authorization, Public, Range, Retry-After, Server, TE, Trailer, Transfer-Encoding, Upgrade, URI, Vary, Via, Warning, and WWW-Authenticate.

Parameters
header:Object — A string that represents an HTTP request header name.
headerValue:String — A string that represents the value associated with header.

Example
The following example adds a custom HTTP header named SOAPAction with a value of Foo to an XML object named my_xml:
my_xml.addRequestHeader("SOAPAction", "'Foo'");

The following example creates an array named headers that contains two alternating HTTP headers and their associated values. The array is passed as a parameter to the addRequestHeader() method.

var headers:Array = new Array("Content-Type", "text/plain", "X-ClientAppVersion", "2.0");
my_xml.addRequestHeader(headers);

See also
LoadVars.addRequestHeader()

createElement Method

public createElement(name:String) : XMLNode

Player version: Flash Player 5

Creates a new XML element with the name specified in the parameter. The new element initially has no parent, no children, and no siblings. The method returns a reference to the newly created XML object that represents the element. This method and the XML.createTextNode() method are the constructor methods for creating nodes for an XML object.

Parameters
name:String — The tag name of the XML element being created.

Returns
XMLNode — An XMLNode object; an XML element.

Example
The following example creates three XML nodes using the createElement() method:
// create an XML document
var doc:XML = new XML();

// create three XML nodes using createElement()
var element1:XMLNode = doc.createElement("element1");
var element2:XMLNode = doc.createElement("element2");
var element3:XMLNode = doc.createElement("element3");

// place the new nodes into the XML tree
doc.appendChild(element1);
element1.appendChild(element2);
element1.appendChild(element3);

trace(doc);
// output: <element1><element2 /><element3 /></element1>

See also
XML.createTextNode()

createTextNode Method

public createTextNode(value:String) : XMLNode

Player version: Flash Player 5

Creates a new XML text node with the specified text. The new node initially has no parent, and text nodes cannot have children or siblings. This method returns a reference to the XML object that represents the new text node. This method and the XML.createElement() method are the constructor methods for creating nodes for an XML object.

Parameters
value:String — A string; the text used to create the new text node.

Returns
XMLNode — An XMLNode object.

Example
The following example creates two XML text nodes using the createTextNode() method, and places them into existing XML nodes:
// create an XML document
var doc:XML = new XML();

// create three XML nodes using createElement()
var element1:XMLNode = doc.createElement("element1");
var element2:XMLNode = doc.createElement("element2");
var element3:XMLNode = doc.createElement("element3");

// place the new nodes into the XML tree
doc.appendChild(element1);
element1.appendChild(element2);
element1.appendChild(element3);

// create two XML text nodes using createTextNode()
var textNode1:XMLNode = doc.createTextNode("textNode1 String value");
var textNode2:XMLNode = doc.createTextNode("textNode2 String value");

// place the new nodes into the XML tree
element2.appendChild(textNode1);
element3.appendChild(textNode2);

trace(doc);
// output (with line breaks added between tags):
// <element1>
//    <element2>textNode1 String value</element2>
//    <element3>textNode2 String value</element3>
// </element1>

See also
XML.createElement()

getBytesLoaded Method

public getBytesLoaded() : Number

Player version: Flash Player 6

Returns the number of bytes loaded (streamed) for the XML document. You can compare the value of getBytesLoaded() with the value of getBytesTotal() to determine what percentage of an XML document has loaded.

Returns
Number — An integer that indicates the number of bytes loaded.

Example
The following example shows how to use the XML.getBytesLoaded() method with the XML.getBytesTotal() method to trace the progress of an XML.load() command. You must replace the URL parameter of the XML.load() command so that the parameter refers to a valid XML file using HTTP. If you attempt to use this example to load a local file that resides on your hard disk, this example will not work properly because in test movie mode Flash Player loads local files in their entirety.
// create a new XML document
var doc:XML = new XML();

var checkProgress = function(xmlObj:XML) {
    var bytesLoaded:Number = xmlObj.getBytesLoaded();
    var bytesTotal:Number = xmlObj.getBytesTotal();
    var percentLoaded:Number = Math.floor((bytesLoaded / bytesTotal )  100);
    trace ("milliseconds elapsed: " + getTimer());
    trace ("bytesLoaded: " + bytesLoaded);
    trace ("bytesTotal: " + bytesTotal);
    trace ("percent loaded: " + percentLoaded);
    trace ("---------------------------------");
}

doc.onLoad = function(success:Boolean) {
    clearInterval(intervalID);
    trace("intervalID: " + intervalID);
}
doc.load("[place a valid URL pointing to an XML file here]");
var intervalID:Number = setInterval(checkProgress, 100, doc);

See also
XML.getBytesTotal()

getBytesTotal Method

public getBytesTotal() : Number

Player version: Flash Player 6

Returns the size, in bytes, of the XML document.

Returns
Number — An integer.

Example
See example for XML.getBytesLoaded().

See also
XML.getBytesLoaded()

load Method

public load(url:String) : Boolean

Player version: Flash Player 5 — The behavior changed in Flash Player 7.

Loads an XML document from the specified URL, and replaces the contents of the specified XML object with the downloaded XML data. The URL is relative and is called using HTTP. The load process is asynchronous; it does not finish immediately after the load() method is executed.

When the load() method is executed, the XML object property loaded is set to false. When the XML data finishes downloading, the loaded property is set to true, and the onLoad event handler is invoked. The XML data is not parsed until it is completely downloaded. If the XML object previously contained any XML trees, they are discarded.

You can define a custom function that executes when the onLoad event handler of the XML object is invoked.

Note: If a file being loaded contains non-ASCII characters (as found in many non-English languages), it is recommended that you save the file with UTF-8 or UTF-16 encoding as opposed to a non-Unicode format like ASCII.

When using this method, consider the Flash Player security model:

For Flash Player 8:

For more information, see the following:

For Flash Player 7 and later websites can permit cross-domain access to a resource via a cross-domain policy file. In SWF files of any version running in Flash Player 7 and later, the url parameter must be in exactly the same domain. For example, a SWF file at www.someDomain.com can load data only from sources that are also at www.someDomain.com.

In SWF files running in a version of the player earlier than Flash Player 7, the url parameter must be in the same superdomain as the SWF file that issues this call. A superdomain is derived by removing the leftmost component of a file's URL. For example, a SWF file at www.someDomain.com can load data from sources at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

The value you pass for the url parameter must be in exactly the same domain. For example, a SWF file at www.someDomain.com can load data only from sources that are also at www.someDomain.com. If you want to load data from a different domain, you can place a cross-domain policy file on the server that is hosting the SWF file.

Parameters
url:String — A string that represents the URL where the XML document to be loaded is located. If the SWF file that issues this call is running in a web browser, url must be in the same domain as the SWF file.

Returns
Boolean — A Boolean value of false if no parameter (null) is passed; true otherwise. Use the onLoad() event handler to check the success of a loaded XML document.

Example
The following code example uses the XML.load() method:
// Create a new XML object.
var flooring:XML = new XML();

// Set the ignoreWhite property to true (default value is false).
flooring.ignoreWhite = true;

// After loading is complete, trace the XML object.
flooring.onLoad = function(success) {
    trace(flooring);
};

// Load the XML into the flooring object.
flooring.load("flooring.xml");

For the contents of the flooring.xml file, and the output that this example produces, see the example for the XML.ignoreWhite property.

See also
XML.ignoreWhite, XML.loaded, XML.onLoad, System.useCodepage

parseXML Method

public parseXML(value:String) : Void

Player version: Flash Player 5

Parses the XML text specified in the value parameter, and populates the specified XML object with the resulting XML tree. Any existing trees in the XML object are discarded.

Parameters
value:String — A string that represents the XML text to be parsed and passed to the specified XML object.

Example
The following example creates and parses an XML packet:
var xml_str:String = "<state name=\"California\">
<city>San Francisco</city></state>" // defining the XML source within the XML constructor: var my1_xml:XML = new XML(xml_str); trace(my1_xml.firstChild.attributes.name); // output: California // defining the XML source using the XML.parseXML method: var my2_xml:XML = new XML(); my2_xml.parseXML(xml_str); trace(my2_xml.firstChild.attributes.name); // output: California


send Method

public send(url:String, [target:String], [method:String]) : Boolean

Player version: Flash Player 5

Encodes the specified XML object into an XML document and sends it to the specified target URL.

When using this method, consider the Flash Player security model:

For more information, see the following:

Parameters
url:String — The destination URL for the specified XML object.
target:String [optional] — The browser window to show data that the server returns:
  • _self specifies the current frame in the current window.
  • _blank specifies a new window.
  • _parent specifies the parent of the current frame.
  • _top specifies the top-level frame in the current window.

If you do not specify a target parameter, it is the same as specifying _self.

method:String [optional] — the method of the HTTP protocol used: either "GET" or "POST". In a browser, the default value is "POST". In the Flash test environment, the default value is "GET".

Returns
Booleanfalse if no parameters are specified, true otherwise.

Example
The following example defines an XML packet and sets the content type for the XML object. The data is then sent to a server and shows a result in a browser window.
var my_xml:XML = new XML("<highscore><name>Ernie</name><score>13045</score></highscore>");
my_xml.contentType = "text/xml";
my_xml.send("http://www.flash-mx.com/mm/highscore.cfm", "_blank");

Press F12 to test this example in a browser.

See also
XML.sendAndLoad()

sendAndLoad Method

public sendAndLoad(url:String, resultXML:XML) : Void

Player version: Flash Player 5 — Behavior changed in Flash Player 7.

Encodes the specified XML object into an XML document, sends it to the specified URL using the POST method, downloads the server's response, and loads it into the resultXMLobject specified in the parameters. The server response loads in the same manner used by the XML.load() method.

When the sendAndLoad() method is executed, the XML object property loaded is set to false. When the XML data finishes downloading, the loaded property is set to true if the data successfully loaded, and the onLoad event handler is invoked. The XML data is not parsed until it is completely downloaded. If the XML object previously contained any XML trees, those trees are discarded.

When using this method, consider the Flash Player security model:

For Flash Player 8:

For more information, see the following:

For Flash Player 7 and later websites can permit cross-domain access to a resource via a cross-domain policy file. In SWF files of any version running in Flash Player 7 and later, the url parameter must be in exactly the same domain. For example, a SWF file at www.someDomain.com can load data only from sources that are also at www.someDomain.com.

In SWF files running in a version of the player earlier than Flash Player 7, the url parameter must be in the same superdomain as the SWF file that is issuing this call. A superdomain is derived by removing the left-most component of a file's URL. For example, a SWF file at www.someDomain.com can load data from sources at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

The value you pass for the url parameter must be in exactly the same domain. For example, a SWF file at www.someDomain.com can load data only from sources that are also at www.someDomain.com. If you want to load data from a different domain, you can place a cross-domain policy file on the server that is hosting the SWF file.

Parameters
url:String — A string; the destination URL for the specified XML object. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see the Description section.
resultXML:XML — A target XML object created with the XML constructor method that will receive the return information from the server.

Example
The following example includes ActionScript for a simple e-commerce storefront application. The XML.sendAndLoad() method transmits an XML element that contains the user's name and password, and uses an onLoad handler to process the reply from the server.
var login_str:String = "<login username=\""+username_txt.text+"\" password=\""+password_txt.text+"\" />";
var my_xml:XML = new XML(login_str);
var myLoginReply_xml:XML = new XML();
myLoginReply_xml.ignoreWhite = true;
myLoginReply_xml.onLoad = myOnLoad;
my_xml.sendAndLoad("http://www.flash-mx.com/mm/login_xml.cfm", myLoginReply_xml);
function myOnLoad(success:Boolean) {
    if (success) {
        if ((myLoginReply_xml.firstChild.nodeName == "packet") &&
            (myLoginReply_xml.firstChild.attributes.success == "true")) {
            gotoAndStop("loggedIn");
        } else {
            gotoAndStop("loginFailed");
        }
    } else {
        gotoAndStop("connectionFailed");
    }
}

See also
XML.send(), XML.load(), XML.loaded, XML.onLoad