|
Flash Media Server Resources |
XML classContents [Hide]The XML class lets you load, parse, send, build, and manipulate XML document trees. Note: You can load XML files only over HTTP, not over
RTMP.
You must use the new XML() constructor to create an XML object before calling any method of the XML class. An XML document is represented by the XML class. Each element of the document is represented by an XMLNode object. The XML and XMLNode objects are modeled after the Document Object Model Level 1 recommendation that can be found on www.w3.org. 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. Note: Many code examples for the XML class include trace() statements.
Server-side trace() statements are output to the
application log file and to the Live Log panel in the Administration
Console.
Property summary
Method summary
Event handler summary
XML constructornew XML([source]) Creates a new XML object. You must use the constructor to create an XML object before you call any of the XML class methods. Note: Use the createElement() and createTextNode() methods
to add elements and text nodes to an XML document tree.
ExampleThe following example creates a new, empty XML object: var my_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 = new XML("<state name=\"California\"><city>San Francisco</city></state>");
XML.addRequestHeader()my_xml.addRequestHeader(headerName, headerValue) my_xml.addRequestHeader([headerName_1, headerValue_1 ... headerName_n, headerValue_n]) Adds or changes HTTP request headers (such as Content-Type or SOAPAction) that are sent with POST actions. In the first usage, you pass two strings, headerName and headerValue, to the method. 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 by 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. Note: A call to XML.addRequestHeader() that
sets a value for the Content-Type header overrides any value set
in the XML.contentType property.
Parameters
ExampleThe 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 = new Array("Content-Type", "text/plain", "X-ClientAppVersion", "2.0");
my_xml.addRequestHeader(headers);
XML.appendChild()my_xml.appendChild(childNode) Appends the specified node to the XML object’s child list. This method operates directly on the node referenced by the childNode parameter; it does not append a copy of the node. If the node to be appended already exists in another tree structure, appending the node to the new location removes it from its current location. If the childNode parameter refers to a node that already exists in another XML tree structure, the appended child node is placed in the new tree structure after it is removed from its existing parent node. Parameters
ExampleThe following example performs these actions:
var doc1 = new XML();
var doc2 = new XML();
// Create a root node and add it to doc1.
var rootnode = doc1.createElement("root");
doc1.appendChild(rootnode);
trace ("doc1: " + doc1); // output: doc1: <root />
trace ("doc2: " + doc2); // output: doc2:
// Move the root node to doc2.
doc2.appendChild(rootnode);
trace ("doc1: " + doc1); // output: doc1:
trace ("doc2: " + doc2); // output: doc2: <root />
// Clone the root node and append it to doc1.
var clone = doc2.firstChild.cloneNode(true);
doc1.appendChild(clone);
trace ("doc1: " + doc1); // output: doc1: <root />
trace ("doc2: " + doc2); // output: doc2: <root />
// Create a new node to append to root node (named clone) of doc1.
var newNode = doc1.createElement("newbie");
clone.appendChild(newNode);
trace ("doc1: " + doc1); // output: doc1: <root><newbie /></root>
XML.attributesmy_xml.attributes An object that contains all the attributes of the specified XML object. Associative arrays use keys as indexes, not ordinal integer indexes that are used by regular arrays. In the XML.attributes associative array, the key index is a string representing the name of the attribute. The value associated with that key index is the string value associated with that attribute. For example, if you have an attribute named color, you would retrieve that attribute’s value by using the color as the key index, as shown in the following code: var myColor = doc.firstChild.attributes.color ExampleThe following example shows the XML attribute names: // Create a tag called 'mytag' with
// an attribute called 'name' with value 'Val'.
var doc = new XML("<mytag name=\"Val\"> item </mytag>");
// Assign the value of the 'name' attribute to variable y.
var y = doc.firstChild.attributes.name;
trace (y);// output: Val
// Create a new attribute named 'order' with value 'first'.
doc.firstChild.attributes.order = "first";
// Assign the value of the 'order' attribute to variable z.
var z = doc.firstChild.attributes.order
trace(z);// output: first
XML.childNodesmy_xml.childNodes Read-only; an array of the specified XML object’s children. Each element in the array is a reference to an XML object that represents a child node. This read-only property cannot be used to manipulate child nodes. Use the XML.appendChild(), XML.insertBefore(), and XML.removeNode() methods to manipulate child nodes. This property is undefined for text nodes (nodeType == 3). ExampleThe following example shows how to use the XML.childNodes property to return an array of child nodes: // Create a new XML document.
var doc = new XML();
// Create a root node.
var rootNode = doc.createElement("rootNode");
// Create three child nodes.
var oldest = doc.createElement("oldest");
var middle = doc.createElement("middle");
var youngest = doc.createElement("youngest");
// Add the rootNode as the root of the XML document tree.
doc.appendChild(rootNode);
// Add each of the child nodes as children of rootNode.
rootNode.appendChild(oldest);
rootNode.appendChild(middle);
rootNode.appendChild(youngest);
// Create an array and use rootNode to populate it.
var firstArray:Array = doc.childNodes;
trace (firstArray);
// Output: <rootNode><oldest /><middle /><youngest /></rootNode>
// Create another array and use the child nodes to populate it.
var secondArray = rootNode.childNodes;
trace(secondArray);
// Output: <oldest />,<middle />,<youngest />
XML.cloneNode()my_xml.cloneNode(deep) Constructs and returns a new XMLNode object of the same type, name, Administration Console value, and attributes as the specified XML object. If deep is set to true, all child nodes are recursively cloned, resulting in an exact copy of the original object’s document tree. The clone of the node that is returned is no longer associated with the tree of the cloned item. Consequently, nextSibling, parentNode, and previousSibling have a value of null. If the deep parameter is set to false, or if my_xml has no child nodes, firstChild and lastChild are also null. Parameters
ExampleThe following example shows how to use the XML.cloneNode() method to create a copy of a node: // Create a new XML document.
var doc = new XML();
// Create a root node.
var rootNode = doc.createElement("rootNode");
// Create three child nodes.
var oldest = doc.createElement("oldest");
var middle = doc.createElement("middle");
var youngest = doc.createElement("youngest");
// Add the rootNode as the root of the XML document tree.
doc.appendChild(rootNode);
// Add each of the child nodes as children of rootNode.
rootNode.appendChild(oldest);
rootNode.appendChild(middle);
rootNode.appendChild(youngest);
// Create a copy of the middle node by using cloneNode().
var middle2 = middle.cloneNode(false);
// Insert the clone node into rootNode between
// the middle and youngest nodes.
rootNode.insertBefore(middle2, youngest);
trace(rootNode);
// Output (with line breaks added):
// <rootNode>
//<oldest />
//<middle />
//<middle />
//<youngest />
// </rootNode>
// Create a copy of rootNode by using cloneNode() to demonstrate a deep copy.
var rootClone = rootNode.cloneNode(true);
// Insert the clone, which contains all child nodes, to rootNode.
rootNode.appendChild(rootClone);
trace(rootNode);
// Output (with line breaks added):
// <rootNode>
// <oldest/>
// <middle/>
// <middle/>
// <youngest/>
// <rootNode>
//<oldest/>
//<middle/>
//<middle/>
//<youngest/>
// </rootNode>
// </rootNode>
XML.contentTypemy_xml.contentType 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. XML.createElement()my_xml.createElement(name) Creates a new XML element with the name specified in the name parameter. The new element initially has no parent, children, or 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. ExampleThe following example creates three XMLNode objects by using the createElement() method: // Create an XML document.
var doc = new XML();
// Create three XML nodes by using createElement().
var element1 = doc.createElement("element1");
var element2 = doc.createElement("element2");
var element3 = 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>
XML.createTextNode()my_xml.createTextNode(text) 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. ExampleThe following example creates two XML text nodes by using the createTextNode() method and places them into existing XML nodes: // Create an XML document.
var doc = new XML();
// Create three XML nodes by using createElement().
var element1 = doc.createElement("element1");
var element2 = doc.createElement("element2");
var element3 = 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 by using createTextNode().
var textNode1 = doc.createTextNode("textNode1");
var textNode2 = doc.createTextNode("textNode2");
// 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</element2>
//<element3>textNode2</element3>
// </element1>
XML.docTypeDeclmy_xml.docTypeDecl 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, <!DOCTYPEgreeting SYSTEM "hello.dtd">). This property is set by using a string representation of the DOCTYPE declaration, not an XMLNode 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 occurs 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, there is no DOCTYPE declaration. XML.firstChildmy_xml.firstChild Read-only; evaluates the specified XML object and references the first child in the parent node’s child list. If the node does not have children, this property is null. If the node is a text node, this property is null. You cannot use this property to manipulate child nodes; use the appendChild(), insertBefore(), and removeNode() methods instead. ExampleThe following example shows how to use XML.firstChild to loop through a node’s child nodes: // Create a new XML document.
var doc = new XML();
// Create a root node.
var rootNode = doc.createElement("rootNode");
// Create three child nodes.
var oldest = doc.createElement("oldest");
var middle = doc.createElement("middle");
var youngest = doc.createElement("youngest");
// Add the rootNode as the root of the XML document tree.
doc.appendChild(rootNode);
// Add each of the child nodes as children of rootNode.
rootNode.appendChild(oldest);
rootNode.appendChild(middle);
rootNode.appendChild(youngest);
// Use firstChild to iterate through the child nodes of rootNode.
for (var aNode = rootNode.firstChild; aNode != null; aNode = aNode.nextSibling) {
trace(aNode);
}
// Output:
// <oldest />
// <middle />
// <youngest />
XML.getBytesLoaded()my_xml.getBytesLoaded() 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. XML.getNamespaceForPrefix()my_xml.getNamespaceForPrefix(prefix) Returns the namespace URI that is associated with the specified prefix for the node. To determine the URI, getPrefixForNamespace() searches up the XML hierarchy from the node, as necessary, and returns the namespace URI of the first xmlns declaration for the given prefix. If no namespace is defined for the specified prefix, the method returns null. If you specify an empty string ("") as the prefix and a default namespace is defined for the node (as in xmlns="http://www.example.com/"), the method returns that default namespace URI. ExampleThe following example creates a very simple XML object and outputs the result of a call to getNamespaceForPrefix(): function createXML() {
var str = "<Outer xmlns:exu=\"http://www.example.com/util\">" + "<exu:Child id='1' />" + "<exu:Child id='2' />" + "<exu:Child id='3' />" + "</Outer>";
return new XML(str).firstChild;
}
var xml = createXML();
trace(xml.getNamespaceForPrefix("exu")); // output: http://www.example.com/util
trace(xml.getNamespaceForPrefix("")); // output: null
XML.getPrefixForNamespace()my_xml.getPrefixForNamespace(nsURI) Returns the prefix that is associated with the specified namespace URI for the node. To determine the prefix, getPrefixForNamespace() searches up the XML hierarchy from the node, as necessary, and returns the prefix of the first xmlns declaration with a namespace URI that matches nsURI. If there is no xmlns assignment for the given URI, the method returns null. If there is an xmlns assignment for the given URI but no prefix is associated with the assignment, the method returns an empty string (""). ExampleThe following example creates a very simple XML object and outputs the result of a call to the getPrefixForNamespace() method. The Outer XML node, which is represented by the xmlDoc variable, defines a namespace URI and assigns it to the exu prefix. Calling the getPrefixForNamespace() method with the defined namespace URI ("http://www.example.com/util") returns the prefix exu, but calling this method with an undefined URI ("http://www.example.com/other") returns null. The first exu:Child node, which is represented by the child1 variable, also defines a namespace URI ("http://www.example.com/child"), but does not assign it to a prefix. Calling this method on the defined, but unassigned, namespace URI returns an empty string. function createXML() {
var str = "<Outer xmlns:exu=\"http://www.example.com/util\">"
+ "<exu:Child id='1' xmlns=\"http://www.example.com/child\"/>"
+ "<exu:Child id='2' />"
+ "<exu:Child id='3' />"
+ "</Outer>";
return new XML(str).firstChild;
}
var xmlDoc = createXML();
trace(xmlDoc.getPrefixForNamespace("http://www.example.com/util")); // output: exu
trace(xmlDoc.getPrefixForNamespace("http://www.example.com/other")); // output: null
var child1 = xmlDoc.firstChild;
trace(child1.getPrefixForNamespace("http://www.example.com/child")); // output: [empty string]
trace(child1.getPrefixForNamespace("http://www.example.com/other")); // output: null
XML.hasChildNodes()my_xml.hasChildNodes() Returns true if the specified XML object has child nodes; otherwise, false. ExampleThe following example creates a new XML packet. If the root node has child nodes, the code loops over each child node to display the name and value of the node. var my_xml = new XML("<login><username>hank</username><password>rudolph</password></login>");
if (my_xml.firstChild.hasChildNodes()) {
// Use firstChild to iterate through the child nodes of rootNode.
for (var aNode = my_xml.firstChild.firstChild; aNode != null; aNode=aNode.nextSibling) {
if (aNode.nodeType == 1) {
trace(aNode.nodeName+":\t"+aNode.firstChild.nodeValue);
}
}
}
The following output appears: username:hank password:rudolph XML.ignoreWhitemy_xml.ignoreWhite XML.prototype.ignoreWhite When set to true, discards, during the parsing process, text nodes that contain only white space. The default setting is false. Text nodes with leading or trailing white spaces are unaffected. Usage 1: You can set the ignoreWhite property for individual XML objects, as shown in the following code: my_xml.ignoreWhite = true; Usage 2: You can set the default ignoreWhite property for XML objects, as shown in the following code: XML.prototype.ignoreWhite = true; ExampleThe following example loads an XML file with a text node that contains only white space; the foyer tag contains 14 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>
The following is the server-side code: // Create a new XML object.
var flooring = new XML();
// Set the ignoreWhite property to true (the 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");
/* output (line breaks added for clarity):
<house>
<kitchen>ceramic tile</kitchen>
<bathroom>linoleum</bathroom>
</foyer>
</house>
*/
If you change the setting of flooring.ignoreWhite to false, or simply remove that line of code entirely, the 14 space characters in the foyer tag are preserved: ...
// Set the ignoreWhite property to false (the default value).
flooring.ignoreWhite = false;
...
/* output (line breaks added for clarity):
<house>
<kitchen> ceramic tile </kitchen>
<bathroom>linoleum</bathroom>
<foyer></foyer>
</house>
*/
XML.insertBefore()my_xml.insertBefore(childNode, beforeNode) Inserts a new child node into the XML object’s child list, before the beforeNode node. If beforeNode is not a child of my_xml, the insertion fails. Parameters
ExampleThe following example is an excerpt from the XML.cloneNode() example: // Create a copy of the middle node by using cloneNode(). var middle2 = middle.cloneNode(false); // Insert the clone node into rootNode // between the middle and youngest nodes. rootNode.insertBefore(middle2, youngest); XML.lastChildmy_xml.lastChild Read-only; an XMLNode value that references the last child in the node’s child list. If the node does not have children, the XML.lastChild property is null. You cannot use this property to manipulate child nodes; use the appendChild(), insertBefore(), and removeNode() methods instead. ExampleThe following example uses the XML.lastChild property to iterate through the child nodes of an XMLNode object, starting with the last item in the node’s child list and ending with the first child of the node’s child list: // Create a new XML document.
var doc = new XML();
// Create a root node.
var rootNode = doc.createElement("rootNode");
// Create three child nodes.
var oldest = doc.createElement("oldest");
var middle = doc.createElement("middle");
var youngest = doc.createElement("youngest");
// Add the rootNode as the root of the XML document tree.
doc.appendChild(rootNode);
// Add each of the child nodes as children of rootNode.
rootNode.appendChild(oldest);
rootNode.appendChild(middle);
rootNode.appendChild(youngest);
// Use lastChild to iterate through the child nodes of rootNode.
for (var aNode = rootNode.lastChild; aNode != null; aNode = aNode.previousSibling) {
trace(aNode);
}
/*
output:
<youngest />
<middle />
<oldest />
*/
The following example creates a new XML packet and uses the XML.lastChild property to iterate through the child nodes of the root node: // Create a new XML document.
var doc = new XML("<rootNode><oldest /><middle /><youngest /></rootNode>");
var rootNode = doc.firstChild;
// Use lastChild to iterate through the child nodes of rootNode.
for (var aNode = rootNode.lastChild; aNode != null; aNode=aNode.previousSibling) {
trace(aNode);
}
/*
output:
<youngest />
<middle />
<oldest />
*/
XML.load()my_xml.load(url) Loads an XML document from a File object or from a URL over HTTP, and replaces the contents of the specified XML object with the XML data. 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 is executed when the onLoad() event handler of the XML object is invoked. Parameters
ExampleThe following simple example uses the XML.load() method: // Create a new XML object.
var flooring = new XML();
// Set the ignoreWhite property to true (the 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("http://somehttpserver/flooring.xml");
For the contents of the flooring.xml file, and the output that this example produces, see the example for XML.ignoreWhite. XML.loadedmy_xml.loaded A boolean value; true if the document-loading process initiated by the XML.load() call completed successfully; otherwise, false. ExampleThe following example uses the XML.loaded property in a simple script: var my_xml = new XML();
my_xml.ignoreWhite = true;
my_xml.onLoad = function(success) {
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 written to the log file when the onLoad() handler is invoked. If the call completes successfully, the loaded status true is written to the log file, as shown in the following example: success:true loaded:true status:0 XML.localNamemy_xml.localName Read-only; the local name portion of the XML node's name. This is the element name without the namespace prefix. For example, the node <contact:mailbox/>bob@example.com</contact:mailbox> has the local name mailbox and the prefix contact, which comprise the full element name contact.mailbox. You can access the namespace prefix by using the XML.prefix property of the XML node object. The XML.nodeName property returns the full name, including the prefix and the local name. ExampleThis example uses a SWF file and an XML file located in the same directory. The XML file, named SoapSample.xml, contains the following code: <?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope">
<soap:Body xmlns:w="http://www.example.com/weather">
<w:GetTemperature>
<w:City>San Francisco</w:City>
</w:GetTemperature>
</soap:Body>
</soap:Envelope>
The source for the SWF file contains the following script (note the comments for the Output strings): var xmlDoc = new XML()
xmlDoc.ignoreWhite = true;
xmlDoc.load("http://www.example.com/SoapSample.xml")
xmlDoc.onLoad = function(success) {
var tempNode = xmlDoc.childNodes[0].childNodes[0].childNodes[0];
trace("w:GetTemperature localname: " + tempNode.localName);
// Output: ... GetTemperature
var soapEnvNode = xmlDoc.childNodes[0];
trace("soap:Envelope localname: " + soapEnvNode.localName);
// Output: ... Envelope
};
XML.namespaceURImy_xml.namespaceURI Read-only; if the XML node has a prefix, the value of the xmlns declaration for that prefix (the URI), which is typically called the namespace URI. The xmlns declaration is in the current node or in a node higher in the XML hierarchy. If the XML node does not have a prefix, the value of the namespaceURI property depends on whether a default namespace is defined (as in xmlns="http://www.example.com/"). If there is a default namespace, the value of the namespaceURI property is the value of the default namespace. If there is no default namespace, the namespaceURI property for that node is an empty string (""). You can use the XML.getNamespaceForPrefix() method to identify the namespace associated with a specific prefix. The namespaceURI property returns the prefix associated with the node name. ExampleThe following example shows how the namespaceURI property is affected by the use of prefixes. The XML file used in the example is named SoapSample.xml and contains the following tags: <?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope">
<soap:Body xmlns:w="http://www.example.com/weather">
<w:GetTemperature>
<w:City>San Francisco</w:City>
</w:GetTemperature>
</soap:Body>
</soap:Envelope>
The source for the Server-Side ActionScript Communication File (ASC file) contains the following script (note the comments for the Output strings). For tempNode, which represents the w:GetTemperature node, the value of namespaceURI is defined in the soap:Body tag. For soapBodyNode, which represents the soap:Body node, the value of namespaceURI is determined by the definition of the soap prefix in the node above it, rather than the definition of the w prefix that the soap:Body node contains. var xmlDoc = new XML();
xmlDoc.load("http://www.example.com/SoapSample.xml");
xmlDoc.ignoreWhite = true;
xmlDoc.onLoad = function(success:Boolean) {
var tempNode:XMLNode = xmlDoc.childNodes[0].childNodes[0].childNodes[0];
trace("w:GetTemperature namespaceURI: " + tempNode.namespaceURI);
// Output: ... http://www.example.com/weather
trace("w:GetTemperature soap namespace: " + tempNode.getNamespaceForPrefix("soap"));
// Output: ... http://www.w3.org/2001/12/soap-envelope
var soapBodyNode = xmlDoc.childNodes[0].childNodes[0];
trace("soap:Envelope namespaceURI: " + soapBodyNode.namespaceURI);
// Output: ... http://www.w3.org/2001/12/soap-envelope
}:
The following example uses XML tags without prefixes. It uses a SWF file and an XML file located in the same directory. The XML file, named NoPrefix.xml, contains the following tags: <?xml version="1.0"?>
<rootnode>
<simplenode xmlns="http://www.w3.org/2001/12/soap-envelope">
<innernode/>
</simplenode>
</rootnode>
The source for the server-side script file contains the following code (note the comments for the Output strings). The rootNode node does not have a default namespace, so its namespaceURI value is an empty string. The simpleNode node defines a default namespace, so its namespaceURI value is the default namespace. The innerNode node does not define a default namespace, but uses the default namespace defined by simpleNode, so its namespaceURI value is the same as that of simpleNode. var xmlDoc = new XML()
xmlDoc.load("http://www.example.com/NoPrefix.xml");
xmlDoc.ignoreWhite = true;
xmlDoc.onLoad = function(success) {
var rootNode = xmlDoc.childNodes[0];
trace("rootNode Node namespaceURI: " + rootNode.namespaceURI);
// Output: [empty string]
var simpleNode = xmlDoc.childNodes[0].childNodes[0];
trace("simpleNode Node namespaceURI: " + simpleNode.namespaceURI);
// Output: ... http://www.w3.org/2001/12/soap-envelope
var innerNode = xmlDoc.childNodes[0].childNodes[0].childNodes[0];
trace("innerNode Node namespaceURI: " + innerNode.namespaceURI);
// Output: ... http://www.w3.org/2001/12/soap-envelope
};
XML.nextSiblingmy_xml.nextSibling Read-only; an XMLNode value that references the next sibling in the parent node’s child list. If the node does not have a next sibling node, this property is null. This property cannot be used to manipulate child nodes; use the appendChild(), insertBefore(), and removeNode() methods to manipulate child nodes. XML.nodeNamemy_xml.nodeName A string representing the node name of the XML object. If the XML object is an XML element (nodeType==1), nodeName is the name of the tag that represents the node in the XML file. For example, TITLE is the node name of an HTML TITLE tag. If the XML object is a text node (nodeType==3), nodeName is null. ExampleThe following example creates an element node and a text node, and checks the node name of each: // Create an XML document.
var doc = new XML();
// Create an XML node by using createElement().
var myNode = doc.createElement("rootNode");
// Place the new node into the XML tree.
doc.appendChild(myNode);
// Create an XML text node by using createTextNode().
var myTextNode = doc.createTextNode("textNode");
// Place the new node into the XML tree.
myNode.appendChild(myTextNode);
trace(myNode.nodeName);
trace(myTextNode.nodeName);
/*
output:
rootNode
null
*/
The following example creates a new XML packet. If the root node has child nodes, the code loops over each child node to display the name and value of the node. Add the following ActionScript to your ASC file: var my_xml = new XML("<login><username>hank</username><password>rudolph</password></login>");
if (my_xml.firstChild.hasChildNodes()) {
// Use firstChild to iterate through the child nodes of rootNode.
for (var aNode = my_xml.firstChild.firstChild; aNode != null; aNode=aNode.nextSibling) {
if (aNode.nodeType == 1) {
trace(aNode.nodeName+":\t"+aNode.firstChild.nodeValue);
}
}
}
The following node names appear: username:hank password:rudolph XML.nodeTypemy_xml.nodeType Read-only; a nodeType value, either 1 for an XML element or 3 for a text node. The nodeType property is a numeric value from the NodeType enumeration in the Document Object Model Level 1 recommendation that can be found on www.w3.org. The following table lists the values:
In Flash Player, the built-in XML class supports only 1 (ELEMENT_NODE) and 3 (TEXT_NODE). ExampleThe following example creates an element node and a text node and checks the node type of each: // Create an XML document.
var doc = new XML();
// Create an XML node by using createElement().
var myNode = doc.createElement("rootNode");
// Place the new node into the XML tree.
doc.appendChild(myNode);
// Create an XML text node by using createTextNode().
var myTextNode = doc.createTextNode("textNode");
// Place the new node into the XML tree.
myNode.appendChild(myTextNode);
trace(myNode.nodeType);
trace(myTextNode.nodeType);
/*
output:
1
3
*/
XML.nodeValuemy_xml.nodeValue The node value of the XML object. If the XML object is a text node, the nodeType is 3, and the nodeValue is the text of the node. If the XML object is an XML element (nodeType is 1), nodeValue is null and read-only. ExampleThe following example creates an element node and a text node and checks the node value of each: // Create an XML document.
var doc = new XML();
// Create an XML node by using createElement().
var myNode = doc.createElement("rootNode");
// Place the new node into the XML tree.
doc.appendChild(myNode);
// Create an XML text node by using createTextNode().
var myTextNode = doc.createTextNode("myTextNode");
// Place the new node into the XML tree.
myNode.appendChild(myTextNode);
trace(myNode.nodeValue);
trace(myTextNode.nodeValue);
/*
output:
null
myTextNode
*/
The following example creates and parses an XML packet. The code loops through each child node and displays the node value by using the firstChild property and firstChild.nodeValue. var my_xml = new XML("<login><username>morton</username><password>good&evil</password></login>");
trace("using firstChild:");
for (var i = 0; i<my_xml.firstChild.childNodes.length; i++) {
trace("\t"+my_xml.firstChild.childNodes[i].firstChild);
}
trace("");
trace("using firstChild.nodeValue:");
for (var i = 0; i<my_xml.firstChild.childNodes.length; i++) {
trace("\t"+my_xml.firstChild.childNodes[i].firstChild.nodeValue);
}
The following information is written to the log file: using firstChild:
morton
good&evil
using firstChild.nodeValue:
morton
good&evil
XML.onData()my_xml.onData = function(src) {}
Invoked when XML text has been completely downloaded from the server or when an error occurs in 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 this situation, 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. If you override it, XML.onLoad() is not called unless you call it in your XML.onData() implementation. Parameters
ExampleThe following example shows what the XML.onData() event handler looks like by default: XML.prototype.onData = function (src) {
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. XML.onHTTPStatus()myXML.onHTTPStatus(httpStatus){}
Invoked when Flash Media Interactive Server 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. After onHTTPStatus() is triggered, onData() is always triggered, whether or not you override onHTTPStatus(). To best use the onHTTPStatus() handler, you should write a function to catch the result of the onHTTPStatus() call; you can then use the result in your onData() and onLoad() handlers. If onHTTPStatus() is not invoked, this indicates that Flash Media Server did not try to make the URL request. If Flash Media Interactive Server cannot get a status code from the server, or if it cannot communicate with the server, the default value of 0 is passed to your ActionScript code. Parameters
ExampleThe following example shows how to use onHTTPStatus() to help with debugging. The example collects HTTP status codes and assigns their value and type to an instance of the XML object. (This example creates the instance members this.httpStatus and this.httpStatusType at runtime.) The onData() handler uses these instance members to trace information about the HTTP response that can be useful in debugging. var myXml = new XML();
myXml.onHTTPStatus = function(httpStatus) {
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) {
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) {
// Insert code here.
}
myXml.load("http://weblogs.macromedia.com/mxna/xml/rss.cfm?query=byMostRecent&languages=1");
XML.onLoad()my_xml.onLoad = function (success) {}
Invoked 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
ExampleThe 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 = "<login username=\""+username_txt.text+"\" password=\""+password_txt.text+"\" />";
var my_xml = new XML(login_str);
var myLoginReply_xml = new XML();
myLoginReply_xml.ignoreWhite = true;
myLoginReply_xml.onLoad = function(success){
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);
XML.parentNodemy_xml.parentNode Read-only; an XMLNode value that references the parent node of the specified XML object or returns null if the node has no parent. This property cannot be used to manipulate child nodes; use the appendChild(), insertBefore(), and removeNode() methods instead. ExampleThe following example creates an XML packet and writes the parent node of the username node to the log file: var my_xml = new XML("<login><username>morton</username><password>good&evil</password></login>");
// The first child is the <login /> node.
var rootNode = my_xml.firstChild;
// The first child of the root is the <username /> node.
var targetNode = rootNode.firstChild;
trace("the parent node of '"+targetNode.nodeName+"' is: "+targetNode.parentNode.nodeName);
trace("contents of the parent node are:\n"+targetNode.parentNode);
/* output (line breaks added for clarity):
the parent node of 'username' is: login
contents of the parent node are:
<login>
<username>morton</username>
<password>good&evil</password>
</login>
*/
XML.parseXML()my_xml.parseXML(source) Parses the XML text specified in the source parameter and populates the specified XML object with the resulting XML tree. Any existing trees in the XML object are discarded. ExampleThe following example creates and parses an XML packet: var xml_str = "<state name=\"California\"><city>San Francisco</city></state>" // Defining the XML source within the XML constructor: var my1_xml = new XML(xml_str); trace(my1_xml.firstChild.attributes.name); // output: California // Defining the XML source by using the XML.parseXML method: var my2_xml = new XML(); my2_xml.parseXML(xml_str); trace(my2_xml.firstChild.attributes.name); // output: California XML.prefixmy_xml.prefix Read-only; the prefix portion of the XML node name. For example, in the node <contact:mailbox/>bob@example.com</contact:mailbox>, the prefix contact and the local name mailbox comprise the full element name contact.mailbox. ExampleA directory contains a server-side script file and an XML file. The XML file, named SoapSample.xml, contains the following code: <?xml version="1.0"?> <soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope"> <soap:Body xmlns:w="http://www.example.com/weather"> <w:GetTemperature> <w:City>San Francisco</w:City> </w:GetTemperature> </soap:Body> </soap:Envelope> The source for the server-side script file contains the following code (note the comments for the Output strings): var xmlDoc = new XML();
xmlDoc.ignoreWhite = true;
xmlDoc.load("http://www.example.com/SoapSample.xml");
xmlDoc.onLoad = function(success) {
var tempNode = xmlDoc.childNodes[0].childNodes[0].childNodes[0];
trace("w:GetTemperature prefix: " + tempNode.prefix); // Output: ... w
var soapEnvNode = xmlDoc.childNodes[0];
trace("soap:Envelope prefix: " + soapEnvNode.prefix); // Output: ... soap
};
XML.previousSiblingmy_xml.previousSibling Read-only; an XMLNode value that references the previous sibling in the parent node’s child list. If the node does not have a previous sibling node, the property has a value of null. This property cannot be used to manipulate child nodes; use the XML.appendChild(), XML.insertBefore(), and XML.removeNode() methods instead. XML.removeNode()my_xml.removeNode() Removes the specified XML object from its parent and deletes all descendants of the node. ExampleThe following example creates an XML packet and then deletes the specified XML object and its descendant nodes: var xml_str = "<state name=\"California\"><city>San Francisco</city></state>";
var my_xml = new XML(xml_str);
var cityNode = my_xml.firstChild.firstChild;
trace("before XML.removeNode():\n"+my_xml);
cityNode.removeNode();
trace("after XML.removeNode():\n"+my_xml);
/* output (line breaks added for clarity):
before XML.removeNode():
<state name="California">
<city>San Francisco</city>
</state>
after XML.removeNode():
<state name="California" />
*/
XML.send()my_xml.send(url, [fileObj]) Encodes the specified XML object into an XML document and sends it to the specified URL by using the POST method in a browser. The Flash test environment uses only the GET method. This method is asynchronous. You can handle the data received in the response in the XML.onData() handler. Parameters
ExampleThe following example defines an XML packet and sets the content type for the XML object. The data is then sent to a server. The result is written in a File object. It is parsed using a custom parsing function called by the onData handler. var my_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", myFile);
my_xml.onData = function(data) {
//custom parsing function
}
See alsoXML.sendAndLoad()my_xml.sendAndLoad(url, targetXMLobject) Encodes the specified XML object into an XML document and sends it to the specified URL using the HTTP POST method. It also downloads the server’s response and loads it into the targetXMLobject object. The server response loads the same as the response to the XML.load() method. When sendAndLoad() is executed, the loaded property is set to false. When the XML data finishes loading successfully, the onLoad() event handler is started. The XML data is not parsed until it is completely downloaded. If the XML object previously contained any XML trees, they are discarded. This method is asynchronous. You can handle the data received in the response in the XML.onData() handler. Parameters
See alsoXML.statusmy_xml.status A number indicating whether an XML document was successfully parsed into an XML object. The following table contains the numeric status codes and their descriptions:
ExampleThe following example loads an XML packet into a SWF file. A status message indicates whether the XML is loaded and parsed successfully. var my_xml = new XML();
my_xml.onLoad = function(success) {
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;
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.flash-mx.com/mm/badxml.xml");
XML.toString()my_xml.toString() Evaluates the specified XML object, constructs a textual representation of the XML structure, including the node, children, and attributes, and returns the result as a string. For top-level XML objects (those created with the constructor), the XML.toString() method outputs the document’s XML declaration (stored in the XML.xmlDecl property), followed by the document’s DOCTYPE declaration (stored in the XML.docTypeDecl property), followed by the text representation of all XML nodes in the object. If the XML.xmlDecl property is undefined, the XML declaration is not output. If the XML.docTypeDecl property is undefined, the DOCTYPE declaration is not output. XML.xmlDeclmy_xml.xmlDecl 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 by using a string representation of the XML declaration, not an XMLNode object. If no XML declaration is encountered during a parse operation, the property is set to undefined.XML. 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. ExampleThe following example loads an XML file and outputs information about the file: var my_xml = new XML();
my_xml.ignoreWhite = true;
my_xml.onLoad = function(success){
if (success){
trace("xmlDecl: " + my_xml.xmlDecl);
trace("contentType: " + my_xml.contentType);
trace("docTypeDecl: " + my_xml.docTypeDecl);
trace("packet: " + my_xml.toString());
}
else {
trace("Unable to load remote XML.");
}
};
my_xml.load("http://foo.com/crossdomain.xml");
|