XQuery concat() Function

The XQuery concat function is used to concatenate various strings.

snippet
concat($input as xs:anyAtomicType?) as xs:string

Parameter explanation:

$input - It specifies one or more inputs separated by comma.

XQuery concat Example

Let's take an example to demonstrate the usage of XQuery concat function. Take an XQuery expression named "books.xqy", having the following code. It will concat the title and price from the given XQuery expression.

XQuery Expression:

books.xqy:

snippet
let $bookTitle := "Learn XQuery in 24 hours"
let $updatedTitle := concat($bookTitle,",price: 200$")
return
   <result>   
      <title>{$updatedTitle}</title>
   </result>

Create a Java based XQuery executor program to read the books.xqy, passes it to the XQuery expression processor, and executes the expression. After that the result will be displayed.

XQueryTester.java

snippet
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQDataSource;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;

import com.saxonica.xqj.SaxonXQDataSource;

public class XQueryTester {
   public static void main(String[] args){
      try {
         execute();
      }
      
      catch (FileNotFoundException e) {
         e.printStackTrace();
      }
      
      catch (XQException e) {
         e.printStackTrace();
      }
   }

   private static void execute() throws FileNotFoundException, XQException{
      InputStream inputStream = new FileInputStream(new File("books.xqy"));
      XQDataSource ds = new SaxonXQDataSource();
      XQConnection conn = ds.getConnection();
      XQPreparedExpression exp = conn.prepareExpression(inputStream);
      XQResultSequence result = exp.executeQuery();
       while (result.next()) {
         System.out.println(result.getItemAsString(null));
      }
   }	
}

Execute XQuery against XML

Put the above both files to a same location. We put them on desktop in a folder name XQuery14. Compile XQueryTester.java using console. You must have JDK 1.5 or later installed on your computer and classpaths are configured.

Compile:

javac XQueryTester.java

Execute:

java XQueryTester

Output:

XQUERY Concat function 1
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +