How to feed Psychopath XPath expressions

Table of Contents

Since PsychoPath has been implemented as an external library and not as a complete program, in order to use it, it needs to be accessed from inside another program. To process XPath 2.0 expressions using PsychoPath from another programs one needs to go through the following process:

  1. Load the XML document

  2. Optionally validate the XML document

  3. Initialize static and dynamic context in respect to the document root

  4. Parse the XPath 2.0 expression

  5. Statically verify the XPath 2.0 expression

  6. Evaluate the XPath 2.0 expression in respect to the XML document

To give a better idea of how this process actually works, we’ll go through an example of processing and evaluating the string expression “Hello World!”. In this example the XML document that we load is called “XPexample.xml”.

All 5 main steps have been explained in detail in User Interface, so below is just a brief code summary:

Non-Schema Aware

/**
* First load and optionally validate the XML document 
*/

// Create an InputStream from the XML document
InputStream is = new FileInputStream("XPexample.xml");

// Initializing the Xerces DOM loader.
DOMLoader loader = new XercesLoader();

// Optionally set flag to validate XML document
// loader.set_validating(validate);
// Loads the XML document and stores the DOM root
Document doc = loader.load(is);

// Initialising the StaticContext using a builder with suitable defaults.
StaticContextBuilder scb = new StaticContextBuilder();

/**
 * Parsing the XPath 2.0 expression into an executable expression, including
 * a static check and verification.
 */
String xpathText = "string-join(//character/name, ', ')";
XPath2Expression expr = new Engine().parseExpression(xpathText, scb);

// Evaluates the XPath 2.0 expression, storing the result
// in the ResultSequence
ResultSequence rs = expr.evaluate(new DynamicContextBuilder(scb),
new Object[] { doc });

for (int i = 0; i < rs.size(); ++i) {
System.out.println("#" + i + ": " + rs.value(i));
}