Search code examples
javaxquerymarklogic

Escaping Scratch-Built XQuery in Java


I'm working on an application that will build and execute XQueries on a MarkLogic server. I'll need to escape some input strings to make sure they don't screw-up the query. Is there any existing Java code that handles this? I'd like to avoid re-inventing this wheel.


Solution

  • Use the built-in language features: XQuery provides external variables, and the XCC API can set them from Java. See http://docs.marklogic.com/javadoc/xcc/overview-summary.html for examples, under "Passing Variables With Queries". Here's a simple one:

    Session session = contentSource.newSession("mydatabase");
    Request request = session.newAdhocQuery(
        "xquery version \"1.0-ml\";\n" +
        "declare variable $myvar as xs:string external;\n" +
        "data($myvar)");
    
    // create Variable "myvar", bind to Request, ignore return value
    request.setNewVariable ("myvar", ValueType.XS_STRING, "Some string value");
    
    // "$myvar as xs:string" will be defined at query run time
    ResultSequence rs = session.submitRequest(request);