如何快速打印groovy.util.slurpersupport.Node?

时间:2012-05-24 20:08:09

标签: xml groovy markupbuilder

有一种简单的方法可以将groovy.util.slurpersupport.Node转换为groovy.util.Node吗?

我正在尝试在来自XmlNodePrinter的节点上使用XmlSlurper,以进行一些快速调试。这是我的代码(可能不是最优雅的):

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
}

这会在config[0]行引发以下内容:

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'

如何快速打印config的xml表示?

我仅限于Groovy 1.7.0。

-

编辑:我也尝试过以下操作但收到错误:

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

这是打印的内容:

[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 个答案:

答案 0 :(得分:5)

对于一些快速调试,最简单的方法是使用XmlUtil

import groovy.xml.*


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

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

println XmlUtil.serialize(a)