Saxon XQuery With Multiple Documents

XQuery CloudSaxon is a wonderful API for XML processing. It provides complete support for XPath, XQuery and XSLT. Although I’m always baffled with it’s lack of adoption compared to Xalan and Xerces. Having said that the online documentation can definitely do with some improvement.  The following is a quick example of of how you may execute an XQuery that takes multiple XML documents as input.

public void runXQueryWithMultipleInputDocuments() throws SaxonApiException {
    Processor processor = new Processor(false);

    DocumentBuilder documentBuilder = processor.newDocumentBuilder();
    XdmNode document =
            new StreamSource(new StringReader("<my><document>content</document></my>")));
    XdmNode document2 =
            new StreamSource(new StringReader("<my><document>content2</document></my>")));

    XQueryCompiler xQueryCompiler = processor.newXQueryCompiler();
    XQueryExecutable xQueryExecutable = xQueryCompiler.compile(
            "declare variable $mydoc external; " +
            "declare variable $mydoc2 external; " +
            "<newdoc><doc1>{$mydoc/my/document/text()}</doc1>" +

    XQueryEvaluator xQueryEvaluator = xQueryExecutable.load();

    QName name = new QName("mydoc");
    xQueryEvaluator.setExternalVariable(name, document);
    QName name2 = new QName("mydoc2");
    xQueryEvaluator.setExternalVariable(name2, document2);


This result is an output of:


One Response to Saxon XQuery With Multiple Documents

  1. mashooq says:

    By the way, if you want to take the result of the XQuery into another evaluator then you’ll need to call asSource() on the returned XDMNode and pass into the build method of the document builder. The resulting XDMNode can be used into another XQuery or XPath evaluator.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: