Process XML via XQuery using Groovy language

I wanted to see an example of XQuery being used in Groovy. Unfortunately, the only example I found would not run with the latest version of MXQuery, so I just fixed it.

XQuery is a standard for querying data. It is not only for XML, but that is what is it is usually associated with. It can be used with CSV, JSON, XML, etc. It is comprehensive enough that one can write applications based on it. See for example the eXist-db database system.

Below the MXQuery library is used, version 0.6.0. For this example, only the single mxquery.jar is required. The example runs two queries. The second query uses the ‘XQuery Update Facility‘ an associated XQuery standard.

Code example

Example source
// require(url:'http://www.mxquery.org', jar:'mxquery.jar', version:'0.6.0')

import groovy.transform.TypeChecked
import ch.ethz.mxquery.contextConfig.*
import ch.ethz.mxquery.query.impl.CompilerImpl
import ch.ethz.mxquery.xdmio.XDMSerializer

/**
 * 
 * Requires MXQuery.jar version 0.6.0
 * @author jbetancourt
 */
@TypeChecked
class XQueryExample {

	static main(args) {
		def query1 = 'for $seq in (1,2,3,4,5) where $seq mod 2 eq 0 return $seq'

		def context = new Context()
		def compiler = new CompilerImpl()

		def result = compiler.compile(context, query1, new CompilerOptions()).evaluate()
		println XDMSerializer.eventsToString(result)

		def query2 = '''
		copy $x := <doc><el><node>this node is deleted</node></el></doc>
		modify
		    (
		       delete node $x/el/node,
		       insert node <node>this node is inserted</node> into $x/el
		    )

			return $x
		
		'''

		def options = new CompilerOptions()
		options.setUpdate(true)

		def transformResult = compiler.compile(context, query2, options).evaluate()
		def xml =new XDMSerializer().eventsToXML(transformResult)

		println XDMSerializer.XMLPrettyPrint(xml.toString())
	}
}

 

The output is:

groovy -cp lib\mxquery\mxquery.jar;src  src\XQueryExample.groovy
0: [12815       xs:integer 2]
1: [12815       xs:integer 4]
2: [64  END_SEQUENCE]

<?xml version='1.0' encoding='UTF-8' ?>

  <doc>
    <el>
      <node>
        this node is inserted
      </node>
    </el>
  </doc>

For original example source see.

Note: For RDF databases there is SPARQL

Links

Standards

Similar Posts:

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Leave a Reply

Your email address will not be published. Required fields are marked *