简体   繁体   中英

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?

This absolutely is supported. See the test suite for the node.js BaseX library .

At the top of your query:

declare variable $variable_name external;

In your code:

query.bind("variable_name", some_value);

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM