## Using PsychoPath XPath 2.0 API

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”.

## 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.setvalidating(validate);
    // Loads the XML document and stores the DOM root
    Document doc = loader.load(is);

    /**
     * Dynamic contexts must be initialised to defaults
     * dependent on the XML Schema.
    */

    // Extracting the schema from DOM root of Xpexpression.xml.
    ElementPSVI rootPSVI = (ElementPSVI)doc.getDocumentElement();
    XSModel schema = rootPSVI.getSchemaInformation();

    // Initialising the DynamicContext.
    DynamicContext dc = new DefaultDynamicContext(schema, doc);

    // Register the namespaces of the XPath 2.0 predefined datatypes
    dc.addnamespace(“xs”,”[http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema]”);

    // Register the XPath 2.0 standard functions
    dc.addfunctionlibrary(new FnFunctionLibrary());
    dc.addfunctionlibrary(new XSCtrLibrary());

    /**
     * Parsing the XPath 2.0 expression into an AST representation
     */
    // Initialises PsychoPath’s supplied parser.
    XPathParser xpp = new JflexCupParser();

    // Parses the XPath expression.
    XPath xp = xpp.parse(xpath);
    /**
     * Static check the AST to verift structural validity of
     * XPath 2.0 expression
     */

    // Initializing StaticChecker.
    StaticChecker namecheck = new StaticNameResolver(sc);

    // Static Checking the Xpath expression ’Hello World!’ namecheck.check(xp);
    /**
     * Evaluate the XPath 2.0 expression
     */

    // Initializing the evaluator with DynamicContext and the name
    // of the XML document XPexample.xml as parameters.
    Evaluator eval = new DefaultEvaluator(dc, doc);

    // Evaluates the XPath 2.0 expression, storing the result
    // in the ResultSequence
    ResultSequence rs = eval.evaluate(xp);