using Xquery, how can I embed variable in an xquery expression on the following xml document. I have the following xml document
<CD>
<TITLE>Picture book</TITLE>
<ARTIST>Simply Red</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Elektra</COMPANY>
<PRICE>7.20</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Red</TITLE>
<ARTIST>The Communards</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>London</COMPANY>
<PRICE>7.80</PRICE>
<YEAR>1987</YEAR>
</CD>
<CD>
<TITLE>Unchain my heart</TITLE>
<ARTIST>Joe Cocker</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>EMI</COMPANY>
<PRICE>8.20</PRICE>
<YEAR>1986</YEAR>
</CD>
I need to issue a query to return all the CDs with YEAR > 1986. I want like to have the components of the "where" clause as variables, I mean storing YEAR > 1986
in to three variables and use the variables in the query, here what I have so far
String queryString =
"declare variable $field :=" +"YEAR"+";"+
"declare variable $operator :=" +">"+";"+
"declare variable $value :=" +"1986"+";"+
"declare variable $docName as xs:string external;" + sep +
"for $cat in doc($docName)/*/"+ "CD" +
"where $cat/$field $operator $value" +
"order by $cat/$field" +
"return $cat";
XQExpression expression = conn.createExpression();
expression.bindString(new QName("docName"), filename,
conn.createAtomicType(XQItemType.XQBASETYPE_STRING));
results = expression.executeQuery(queryString);
return results.getSequenceAsString(new Properties());
My query expression isn't perfect, I think I am having trouble in using the variables, any one can help me in solving this please? Thanks
Variables in XQuery (and XSLT/XPath) represent values, not fragments of program text. That is, it's not a macro language - variables don't work by textual substitution.
Using a variable for the value is straightforward: x = $value.
Using a variable for the element name isn't too difficult: *[name()=$n] = $value
But using a variable for the operator isn't possible. When you get to this level it's better to generate the query as a string using string concatenation, and then compile it and execute it. In fact you seem to be generating the query as a string anyway (without worrying about the risk of code injection, I see).
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.