« Automating Meta Data insertion using JSAPI | Main | Understanding ExternalInterface in Flash 8 »

Using the XPath API in Flash

Listen to this article Listen to this article :: Talkr

What is XPath?

XPath is a simple way by which you search through a XML document. It lets you query XML documents using names instead of the firstChild.childNodes... method.
If you are looking for a detailed explanation you can find one here : XML Path Language (XPath). This is what is mentioned in Macromedia LiveDocs about the use of XPath:

"The XPathAPI class allows you to do simple XPath searches within Macromedia Flash. This can be very useful for searching XML packets based on node names and attribute values. In other words, you can quickly find nodes and attributes in an XML document using the XpathAPI methods."

At this point I have to mention that Flash does not support all the functionalities of XPath API as defined by the XPath standard documents. Flash provides support to only a small subset of the XPath API.

What's the use of XPath?

XPath saves lot of time which you spend figuring out which node/s you want to target and retrieve value from. XPath existed from MX2004 days but wasn't documented, but in Flash 8 it is documented. Flash 8's in build help doesn't provide much of details on using XPath but there is a link to the LiveDocs which points to a PDF file which has all the public methods listed and examples for using them.

How to use XPath in Flash?

There are two things that you have to do to get XPath working. The first is to import the XPathAPI class like this:

import mx.xpath.XPathAPI;

and next to have a instance of DataBinding classes (Window > Common Libraries > Classes) in your document. You can drag a instance of the DataBinding class into your document.

Now you are ready to start using the XPath API.

The XPath API class contains the following public methods:

XPathAPI.getEvalString()
XPathAPI.selectNodeList()
XPathAPI.selectSingleNode()
XPathAPI.setNodeValue()

In this tutorial I am going to deal with two of these API's XPathAPI.selectNodeList() and XPathAPI.selectSingleNode()

XPathAPI.selectNodeList()

This method retrieves the nodes of a specified node path.

Syntax:

XPathAPI.selectNodeList(node, path)

Let’s start with an example XML of the site index of this site

Have a look at the actual XML here.

Now if I want to retrieve the value of all the title's, the path would be \rss\channel\item\title and the node would be this.firstChild.
So in this case I would use the selectNodeList as:

XPathAPI.selectNodeList(this.firstChild, "/rss/channel/item/title");

This statement would return me the array of all the titles.

Example:

import mx.xpath.XPathAPI;

var rss:XML = new XML();
rss.ignoreWhite = true;
rss.onLoad = function(success:Boolean) {
if (success) {
// Retrieve all titles in the path /rss/channel/item/title.
var titleArray:Array = XPathAPI.selectNodeList(this.firstChild, "/rss/channel/item/title");
for (var i:Number = 0; i < titleArray.length; i++) {
trace(titleArray[i].firstChild.nodeValue);
}
} else {
trace("XML loading failed !!!");
}
};
rss.load("http://www.lastashero.com/tutorials/index.xml");

This code will trace the following values in the output window :

Automating Meta Data insertion using JSAPI
Using SWF Metadata in Flash 8
Creating a File upload application using FileReference API
Using the onHTTPStatus handler
Flash 8 - Object Drawing Model

XPathAPI.selectSingleNode()

XPathAPI.selectSingleNode method is very similar to XPathAPI.selectNodeList, except for the fact that XPathAPI.selectSingleNode retreives the value of a single node instead of multiple nodes as in XPathAPI.selectNodeList.

Syntax:

XPathAPI.selectSingleNode(node, path)

Going by the old example, if you want to retrieve the value of the first title node the code would be :

import mx.xpath.XPathAPI;

var rss:XML = new XML();
rss.ignoreWhite = true;
rss.onLoad = function(success:Boolean) {
if (success) {
// Retrieve the title of the first node in the path /rss/channel/item/title.
var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/channel/item/title");
trace(titleNode.toString());
} else {
trace("XML loading failed !!!");
}
};
rss.load("http://www.lastashero.com/tutorials/index.xml");

This code will trace the following values in the output window :

<title>Automating Meta Data insertion using JSAPI</title>

The following path expressions can be used for the query:

Absolute path :

/item/title

Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/channel/item/title");

Relative path :

title (if the context node is )

Example: Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "title");

Wildcard (*) :

/*/title - retrieves all <title> elements,whatever the parent node is

Example : var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/*/title");

Predicate expressions using =, AND, or OR :

/item/title[@version='current']
or:
/item/title[@version='current' AND
@post='today']

Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/item/title[@version='current' AND @post='today']");

Documentation:

You can download the PDF from LiveDocs which contains all the methods and the usage from here.

If you have Flash 8 Pro / MX2004 Pro installed you can check out the actual class here :

C:\Documents and Settings\[User]\Local Settings\Application Data\Macromedia\Flash 8\[Language]\Configuration\Classes\mx\xpath\

Related readings:

XPath in Flash
Using XPath with Flash
XPath in Flash - there's always more than one way to go
Using XPath in Flash


TrackBack

TrackBack URL for this entry:
http://www.lastashero.com/tutorials/mt-tb.cgi/6

Listed below are links to weblogs that reference Using the XPath API in Flash:

» Recursos XPath para Flash from Joan | Garnet
XML Path (XPath) es un lenguaje para realizar búsquedas en documentos XML. Para entendernos se podría decir que es una especie de SQL para XML (aunque solo relaliza operaciones de búsqueda). - Especificación completa: XML Path language - Referencia... [Read More]

Questions & Comments

why doesn't XPath 'selectSingleNode' return an XMLNode rather than a String?

var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/*/title");

cheers p;)

this tutorial is really very useful and very self explanatory.thank u

Dear,
please help me in flash Make action script

Regards
Mukesh

Gotta say this comes as surprise to me.. was just using the tedious ChildNodes.firstChild method as recent as yesterday, and this is much more fun..

And even better, the query is just like the XML Path Language .. sweet :)

Thanks, man.. this is just so sweet [repeat 5x]

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)