1

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

Community
  • 1
  • 1
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • Similar problem here, with good answer: http://stackoverflow.com/questions/3030903/content-is-not-allowed-in-prolog-when-parsing-perfectly-valid-xml-on-gae – Paweł Piecyk Aug 20 '14 at 06:12
  • Thanks for response @PawełPiecyk, but that doesn't seems to solve my problem, since I don't have new xml in string. And also the above code is working in a console window but not in a grails script. – Shashank Agrawal Aug 20 '14 at 06:43
  • 1
    Does this help? https://www.jayway.com/2013/04/09/serializing-groovy-util-slurpersupport-node-to-xml/ – mvmn Sep 22 '16 at 06:52
  • Okay, I'll try. Thanks for the effort – Shashank Agrawal Sep 22 '16 at 07:45

1 Answers1

1

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))
    }
}
coz
  • 445
  • 8
  • 14