How do I quickly print a groovy.util.slurpersupport.Node?

4.4k Views Asked by At

Is there an easy way to convert a groovy.util.slurpersupport.Node to a groovy.util.Node?

I am trying to use the XmlNodePrinter on a node coming from an XmlSlurper, for some quick debugging. Here is my code (probably not the most elegant):

def xml = new XmlSlurper().parse( new File( path + pomFile ) )
def services = xml.build.plugins.plugin.configuration.services
services.children().findAll{ it.artifactId.text() == serviceName }.each { config ->

    // begin section to dump "config" for debugging
    def stringWriter = new StringWriter()
    new XmlNodePrinter(new PrintWriter(stringWriter)).print(config[0])
    println stringWriter.toString()
    // end section to dump "config" for debugging

    // do some other processing on the config node
}

This throws the following on the config[0] line:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'groovy.util.slurpersupport.Node@14712c3' with class 'groovy.util.slurpersupport.Node' to class 'groovy.util.Node'

How can I quickly print out the xml representation of config?

I am limited to Groovy 1.7.0.

-

EDIT: I also tried the following but receive an error:

services.children().findAll{ it.artifactId.text() == serviceName }.each { config ->
     println XmlUtil.serialize(config)

Here's what's printed:

[Fatal Error] :1:1: Content is not allowed in prolog.
ERROR:  'Content is not allowed in prolog.'
<?xml version="1.0" encoding="UTF-8"?>
1

There are 1 best solutions below

1
Luis Muñiz On

for some quick debugging, the simplest way is to use XmlUtil

import groovy.xml.*


def xml="""
<a><b>b</b><c/></a>
"""

def a=new XmlSlurper().parseText(xml)

println XmlUtil.serialize(a)