Shashank Agrawal
Shashank Agrawal

Reputation: 25797

Groovy's XMLUtil serialize method not working

I'm modifying a xml file using groovy's XMLSlurper and writing it back using groovy's XMLUtil.

def xml = new XmlSlurper(false,false).parseText(new File("pom.xml").text)

// Append new elements or nodes
xml.appendNode {
    pluginRepositories {
        pluginRepository {
            id 'synergian-repo'
            url 'https://raw.github.com/synergian/wagon-git/releases'
        }
    }
}

// Write back to original file.
XmlUtil.serialize(xml, new File("pomm.xml").newPrintWriter("UTF-8"))

This working fine, when I'm doing this by launching grails console. But throwing an error when using this code in a grails script.

[Fatal Error] :1:1: Content is not allowed in prolog.
| Error ERROR:  'Content is not allowed in prolog.'
| Error Error executing script ReleasePlugin: groovy.lang.GroovyRuntimeException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog. (NOTE: Stack trace has been filtered. Use --verbose to see entire trace.)
groovy.lang.GroovyRuntimeException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
    at ReleasePlugin$_run_closure1.doCall(ReleasePlugin:96)

Note: Line 96 is the line of XMLUtil serialization, where I'm writing the xml back.

Using grails 2.3.5 with jdk 1.7

Modify existing xml file in Groovy

Upvotes: 1

Views: 6461

Answers (1)

coz
coz

Reputation: 486

Since OP never bother to provide the feedback, here is what it worked for me based on mvmn comment.

The solution is to wrap the groovy.util.slurpersupport.Node in an instance of groovy.util.slurpersupport.NodeChild before passing it to XmlUtil:

import groovy.util.slurpersupport.Node
import groovy.util.slurpersupport.NodeChild
import groovy.xml.XmlUtil

class GroovyNodeSerializer {
    static String toXML(Node node) {
        return XmlUtil.serialize(new NodeChild(node, null, null))
    }
}

Upvotes: 2

Related Questions