[an error occurred while processing this directive]
> developer > web app development
Tips on when to use xPath and when to use ECMAScript
by exteNd Composer Product Team, eBusiness Integration Products, Novell
Date Created: 2001-01-22 10:48:00.000
  Introduction
  XPath
  ECMAScript with XPath
introduction
XML Document manipulation using just XPath features is contrasted against using ECMAScript and XPath.

Fundamental to xCommerce's role as an XML transformation engine is its ability to manipulate XML documents.  To manipulate XML, xCommerce implements various standards recommended by the World Wide Web consortium.  These include the XPath specification, the Document Object Model (DOM), and the ECMAScript to DOM binding. 

Given this set of technologies it can be confusing sometimes deciding when to use each one.  The above diagram demonstrates xCommerce philosophy of providing very easy to use GUI tools to the user while also offering a very layered approach to access more powerful but difficult tools.  At the top layer you have the GUI actions, each of which has direct access to XPath as well as the programmability of the underlying ECMAScript processor.  ECMAScript in turn can access Java through a very thin and direct interface.

Assuming we have a component that has been handed an Input XML document there are four ways one could work with that document, each with their own advantages and disadvantages.  A major benefit of xCommerce's architecture is the smooth integration of all of these methods that doesn't lock you into one at the expense of using the others.  The four methods are outlined in the remainder of this article.

XPath

The basic manipulation in xCommerce is the Map Action which allows you to map nodes (Elements, Attributes, etc.) from one XML document into nodes of another XML document.  The default mechanism for specifying the Source and Target of the Map action is an XPath Location path expressed in a fashion similar to directory hierarchies under DOS (e.g. ROOT/CHILD/CHILD).  There are two critical concepts to understand with XPath in xCommerce.  The first is that an XPath expression always returns a list of nodes matching the XPath pattern in the form of a NodeList object.  Second, the default behavior for a Map action is to process only the first Node in the list (processing the entire list is handled explicitly by the Repeat for Element action). 

On the surface it appears XPath will run out of gas rather quickly, especially if one wants to do more than just map a single element or attribute.  However, when the Map action is combined with the Repeat for Element and Repeat for Group actions, XPath proves to very powerful indeed, especially in specifying a NodeList within a document and across multiple documents.  For instance, if your component has two Input documents, each containing multiple ADDRESS elements at different locations within their respective hierarchies.  XPath provides flexible wildcard expressions to return a NodeList containing ALL the ADDRESSes.  The example below is a powerful demonstration of this with a Repeat for Element loop that collects all the ADDRESSes in a NodeList and processes each one with a Map action inside the loop transferring each ADDRESS to the Output document.

Another example is the XPath String function: translate().  This XPath function allows you to make character substitutions.  In the following example, an element using dashes as delimiters in the phone number, is mapped with the translate() function replacing the dashes with a period (American format 212-123-1234 to European style 212.123.1234).

A sample project that you can download is available (http://ftp1.novell.com/pub/xcommerce/XPathFeatures.zip) that makes exploring the following features of XPath time well spent, as it will allow you to use Designer's GUI to its fullest and speed up your project development time.

Location Path operators:

selector brackets ( [ ] ) = specify a position in the NodeList, slash ( / ) = childnode, double slash ( // ) = any matching node, asterisk ( * ) = positional any matching node, vertical bar ( | ) = union

NodeSet Functions:

count(), last(), position(), name(), ID(), local-name(), namespace-uri()

String Functions:

concat(), string(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(), normalize-space(), translate()

Boolean Functions:

boolean(), not(), true(), false(), lang()

Number Functions:

number(), sum(), floor(), ceiling(), round()

Advantages

XPath expressions can be automatically generated by the XPath expression builder.

Uses a familiar syntax (directory structure slashes) for expressing locations in an XML document hierarchy.

Good document node selection capability across multiple documents.

Contains some easily used and very handy functions (NodeSets, String, Boolean, and Number).

Usable from the Decision, Function, Log, Map, Repeat for Element, Send Mail, Process XSL, Raise Error, Repeat for Group, Repeat While, and XML Interchange actions.

Disadvantages

Limited set of built in functions.

Lacks programmability.

Restricted to manipulating documents at relatively large levels of granularity.

ECMAScript with XPath

To perform more complex or specialized manipulations of XML documents you will need to use ECMAScript.  This is why the Map Action dialog has the radio button  controls for XPath and Expression.  XPath is the default and means you wish to specify the Source and Target for the Map action in pure XPath syntax.  Selecting Expression means you want to specify the Source or Target as an ECMAScript expression using that language's syntax and features.  Expression allows you to use the robust Math, String, and Number objects against your XML document as well as programmatic scripts complete with variable declarations, loop command structures, and other programming constructs.

The key concept to know when working in this environment is that the reserved document names: Input, Input1, Inputn, Temp, Temp1, Tempn, and Output are known to ECMAScript as objects.  The second key concept to know is that these objects have an ECMAScript to XPath bridge method called XPath().  So if you wish to still use XPath within the ECMAScript context you can.

Here is the same ADDRESS processing example as shown earlier, instead using ECMAScript bridging to XPath syntax.  First create a Custom Script with a function named "myAddressScript" as follows:

function myAddressScript(Input, Input1, Output)

{

  var MyAddrIndex = 1;

  for( var AllAddr in Input.XPath("//ADDRESS | $Input1//ADDRESS"))

  {

    var MyAddr = Output.createXPath("MYLIST/AnADDRESS[$MyAddrIndex]")

    MyAddr.createXPath(".").setValue(AllAddr.XPath("."));

    MyAddrIndex++;

    //

    // do other stuff here you can't do with pure XPath manipulations...

    //

  }

}

Then we call the function from a Function Action in a Component...

The xCommerce distribution CD installs a variety of Custom Script libraries with over a 100 script functions categorized as follows: Database, Date, DOM, File, General, Math, and String.  You can easily Import or copy these into your own projects and begin using them right away.  The source for these scripts is in your xCommerce installation directory: xCommerce/Samples/CustomScripts.

Advantages

Can manipulate a document with a finer level of programmatic control.

ECMAScript Math, String and Number objects provide a robust complement to the XPath functions.

You can create reusable and sophisticated Custom Scripts to operate on an XML document.

Custom Scripts are also callable from most actions within a component.

Disadvantages

More verbose expressions than pure XPath.

Can be more time consuming to write ECMAScript code.