Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Groovy's XML capabilities are powerful enough that you may not need to consider other alternatives such as XQuery. If you wish to use XQuery though, it isn't hard to do. Here we just added mxquery.jar from the MXQuery project to our CLASSPATH. MXQuery is still under development and may not support all of XQuery yet but it appears to be making good progress and has a relatively small footprint.
Once our path is set up, we can run the following script:

Code Block
// require(url:'http://www.mxquery.org', jar:'mxquery.jar', version:'0.2.1')
import ch.ethz.mxquery.util.IteratorPrinter
import ch.ethz.mxquery.core.XQueryRuntime

def query = '''
(: DESCRIPTION: Deletes and inserts a node in a transform expression. :)

transform
    copy $x := <doc><el><node>this node is deleted</node></el></doc>
    modify
    (
        do delete $x/el/node,
        do insert <node>this node is inserted</node> into $x/el
    )
    return $x/el
'''
def runtime = new XQueryRuntime()
def exp = runtime.prepareQuery(query)
def result = exp.evaluate()
println IteratorPrinter.eventsToXML(result)
// => <el><node>this node is inserted</node></el>

Or using a later version of the library:

Code Block

// require(url:'http://www.mxquery.org', jar:'mxquery.jar', version:'0.4.1')
import ch.ethz.mxquery.query.Context
import ch.ethz.mxquery.query.impl.CompilerImpl
import static ch.ethz.mxquery.util.IteratorPrinter.*

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).evaluate()
println eventsToString(result)
// =>
// 0: [12815	xs:integer 2]
// 1: [12815	xs:integer 4]
// 2: [64	END_SEQUENCE]

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/el
'''
result = compiler.compile(context, query2).evaluate()
println XMLPrettyPrint(eventsToXML(result).toString())
// =>
// <el>
//   <node>
//     this node is inserted
//   </node>
// </el>

...