groovygroovy-consolegroovy-eclipse

MarkupBuilder in Eclipse: unable to resolve class groovy.xml.markupBuilder


I feel a bit silly for making this question, but I'm out of options.

Basically, I have this on a "let's learn groovy" project:

package com.mypackage.markupexercise

import groovy.xml.MarkupBuilder

println "Hello MarkupBuilder"

def writer = new StringWriter()
def builder = new MarkupBuilder(writer)

builder.records() {
    example(id:1)
}

And I'm getting the following compilation error:

<path>\markupbuilderexercise\Main.groovy: 3: unable to resolve class groovy.xml.MarkupBuilder
 @ line 3, column 1.
   import groovy.xml.MarkupBuilder
   ^

1 error

Now, I've seen [this question][1], and I have imported the groovy-xml-3.09.jar file (Through right click on project -> Properties -> Java Build Path -> Add Jars...)

There is nothing on the "Problems" tab, and if I try to run through the groovy console, I get the following error:

groovy.lang.MissingMethodException: No signature of method: groovy.xml.MarkupBuilder.records() is applicable for argument types: (com.neuro.groovyhelloworld.markupbuilderexercise.Main$_run_closure1) values: [com.neuro.groovyhelloworld.markupbuilderexercise.Main$_run_closure1@2e757861]

    at com.neuro.groovyhelloworld.markupbuilderexercise.Main.run(Main.groovy:10)

    at com.neuro.groovyhelloworld.markupbuilderexercise.Main.main(Main.groovy)

My take here is that I'm not adding the dependency in the right way, but I'm a Java developer and dependencies were either what I've done or just relying on Maven/Gradle, so I'm kind of out of ideas here.

What am I missing?

  [1]: https://stackoverflow.com/questions/59132101/eclipse-groovy-unable-to-resolve-class

Solution

  • I see the same issue when choosing Run As > Groovy Console and then running the script. It does work fine for Run As > Groovy Script on the following source -- I used grab so I didn't need to add groovy-xml to my project's classpath:

    @Grab('org.codehaus.groovy:groovy-xml:3.0.9')
    import groovy.xml.MarkupBuilder
    
    def writer = new StringWriter()
    new MarkupBuilder(writer).tap {
      records {
        example(id:1)
      }
    }
    
    print writer
    

    I get the following output:

    <records>
      <example id='1' />
    </records>
    

    You can also build the project and run the script using Run As > Java Application.