Problem using the groovy DOMBuilder inside gradle task

(eirik.lygre) #1

We’re trying to manipulate a pom inside the withXml-closure, and found some problems. Here is the gist of what we see:

task xml << {
        def xml = "<document><chapter>ChapterContent</chapter></document>"
        println groovy.xml.DOMBuilder.parse (new StringReader(xml)).documentElement
  c:\temp>gradle xml
[document: null]

Using the groovyConsole (groovy 1.8.4), it looks entirely different:

groovy> def xml = "<document><chapter>ChapterContent</chapter></document>"
 groovy> println groovy.xml.DOMBuilder.parse (new StringReader(xml)).documentElement
    <?xml version="1.0" encoding="UTF-8"?>

Am I doing something horribly wrong here, or did something go horribly wrong elsewhere?

(Peter Niederwieser) #2

I have no idea what’s going on here. Is there a reason why you aren’t using ‘XmlProvider.asElement()’? (An instance of ‘XmlProvider’ is passed to the ‘withXml’ closure). Another option is to use ‘XmlProvider.asNode()’ together with Groovy’s ‘XmlParser’.

(eirik.lygre) #3

The use case is to insert a fragment into the existing document passed to code>withXml. We have problems with a maven build (really only the site plugin) failing due to some bad dependencies being introduced by a third party component, and want to insert exclusion rules. I’m looking for something like the code below; the original example was an attempt to isolate the problem:

String exclusionsString = """
def exclusions = groovy.xml.DOMBuilder.parse(new StringReader(exclusionsString), false, false)
withXml { xml ->
    // Insert "exclusions" into xml.asElement(), somewhere

So I guess there are two issues:

  1. What is the best way of solving my “business need”, ie to insert an xml-fragment into XmlProvider? 2) Is it reasonable for the original code to fail (“my fault”), or should it have worked (“gradle’s fault”)?

(Adam Murdoch) #4

I think what you’re seeing is that when you run the task and when you run from the Groovy console, you are ending up with different DOM implementations, which have different ‘toString()’ implementations. The content of the document is still the same. For example, if you change your sample code to this:

task xml << {
    def xml = "<document><chapter>ChapterContent</chapter></document>"
    def element = groovy.xml.DOMBuilder.parse (new StringReader(xml)).documentElement
    println groovy.xml.XmlUtil.serialize(element)

you end up with this output:

<?xml version="1.0" encoding="UTF-8"?>

(Peter Niederwieser) #5

I thought that too, but element.getClass().getName() was the same in both cases (com.sun…)