node.jsxquerybasexxml-database

Using outer variables in an XQuery expression


I am using BaseX database server with a Node.js application. The application allows a user to input multiple strings in a textfield separated by a delimiter. These multiple strings are then to be queried to the XML file to search for nodes having the same value. I don't have any idea how to include the outer variable splitstring in the XQuery. Here's my code:

exports.search = function(req, res){

var string = req.body.searchBox;
string = string.toLowerCase();
var splitstring = string.split(' ');
//console.log(splitstring);
var basex = require('basex');
var log = require("../node_modules/basex/debug");

// create session
var session = new basex.Session();
basex.debug_mode = false;

// create query instance
var inputquery = 'for $node in doc("./tags.xml")/images/image return $node/source';
var query = session.query(inputquery);

query.results(log.print);

// close query instance
query.close();

// close session
session.close(); 

I want to implement something like this:

var inputquery = 'for $node in doc("./tags.xml")/images/image where $node/tag=' + <one of the strings in splitstring> + ' return $node/source';

Can something like this be done using BaseX and XQuery?


Solution

  • Extending on what Charles Duffy already correctly suggested, here is an example to bind the complete string and tokenize it within XQuery. You bind the value and define the value as external within XQuery. Splitting a string within XQuery is simply done by using fn:tokenize()

    // create query instance
    var inputquery = 'declare variable $string as xs:string external;' +
      'for $node in doc("./tags.xml")/images/image where $node/tag=tokenize($string, "\s") return $node/source';
    var query = session.query(inputquery);
    query.bind("string", string);
    query.results(log.print);
    query.close();