Groovy XmlUtil.serialze() is throwing a 'Content is not allowed in prolog' error when trying to serialize a GPathResult
I've encountered a strange issue with Groovy's (1.7.3) XmlUtil.serialize( GPathResult ) method. It throws a 'Content is not allowed in prolog' error when I call it with a GPathResult, but groovy.util.Node is serializing just fine. Here is the very simple Groovy Script I am trying:
import groovy.xml.XmlUtil
import groovy.xml.StreamingMarkupBuilder
def xmlStr = """<?xml 开发者_如何学Cversion="1.0" encoding="UTF-8"?><stuff>ver="1.0"><properties><foo>bar</foo></properties></stuff>"""
//to pretty print GPathResult -- NOT WORKING
def gpr = new XmlSlurper().parseText( xmlStr )
println XmlUtil.serialize( gpr )
println 'trying groovy.util.Node'
//to pretty print groovy.util.Node -- WORKS
def node = new XmlParser().parseText( xmlStr )
println( XmlUtil.serialize( node ) )
This is the output I get:
[Fatal Error] :1:1: Content is not allowed in prolog.
ERROR: 'Content is not allowed in prolog.'
<?xml version="1.0" encoding="UTF-8"?>
trying groovy.util.Node
<?xml version="1.0" encoding="UTF-8"?>
<stuff ver="1.0">
<properties>
<foo>bar</foo>
</properties>
</stuff>
I am using Groovy Version: 1.7.3 JVM: 1.6.0_20 on Mac OS X Snow Leopard
Is anyone else experiencing this?
Looks like a bug where Groovy is selecting the wrong serialize
method to execute in XmlUtil
If we hard-cast it, it seems to work for me (does it for you?)
println XmlUtil.serialize( (groovy.util.slurpersupport.GPathResult)gpr )
I've added it to the JIRA here: http://jira.codehaus.org/browse/GROOVY-4285 So hopefully, it will be fixed in future releases, and you won't need the cast
[edit] The JIRA now states that a fix has gone into trunk, and will be generally available in 1.7.4+
You could just use Simple as an alternative to Groovy XmlUtil.
精彩评论