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:
Load the XML document
Optionally validate the XML document
Initialize static and dynamic context in respect to the document root
Parse the XPath 2.0 expression
Statically verify the XPath 2.0 expression
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:
/**
* 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));
}