What's new? | Help | Directory | Sign in
Google
xpath-as3
An XPath implementation for ActionScript 3.0
  
  
  
  
    
Search
for
Updated Dec 03, 2007 by peterjoel
Labels: Featured
GettingStarted  

Basic overview of how to use the XPath library

Executing XPath Statements

XPath queries are evaluated using the XPathQuery object.

// create the XPathQuery instance and parse the path
var myQuery:XPathQuery = new XPathQuery("path/to/evaluate");
// execute the statement on an XML object and get the result
var result:XMLList = myQuery.exec(myXML);

Using namespaces

The easiest way to select nodes that are in XML namespaces is via the openAllNamespaces property, though it might not be the safest if there are several namespaces used in the document, with conflicting local names.

var myQuery:XPathQuery = new XPathQuery("path/to/evaluate");
myQuery.context.openAllNamespaces = true;

To do it properly, you need to register namespace prefixes with the corresponding URI. This prefix does not need to match the prefix used in the XML document, but must match the prefix that you use in your XPath statements.

var myQuery:XPathQuery = new XPathQuery("ns1:path/to/ns2:evaluate");
myQuery.context.namespaces["ns1"] = "http://domain.com/2006/ns1";
myQuery.context.namespaces["ns2"] = "http://domain.com/2007/ns2";

The XPathContext object

The XPathContext object is how you can specify namespaces, variables and custom functions to use in your XPath statements. By creating an instance of XPathContext, you can pass it as an argument to the constructor all of your XPathQueries, so you do not have to set them all up individually.

// create the context instance
var context:XPathContext = new XPathContext();
// declare a namespace
context.namespaces["ns1"] = "http://domain.com/2006/ns1";
// define a custom variable
context.variables["myCustomVar"] = true;
// Pass the context to the XPathQuery instance
var myQuery:XPathQuery = new XPathQuery("path/to/evaluate", context);

Alternatively, you can customise the default XPathContext, which will then apply to all XPathQueries, as long as you don't also pass one as an argument.

// this namespace will be available to all XPathQuery objects
XPathQuery.defaultContext.namespaces["ns1"] = "http://domain.com/2006/ns1";

Comment by bradbeattie, Aug 27, 2007

"myQuery.openAllNamespaces = true;" should instead read "myQuery.context.openAllNamespaces = true;"

Comment by peterjoel, Dec 03, 2007

Thanks. I fixed that now.

Comment by leeanthonysutton, Apr 04, 2008

Does XPathQuery support the "translate" operation for searching and ignoring case?

Comment by peterjoel, May 06, 2008

Yes it supports translate.


Sign in to add a comment