Dan Tanner
Dan Tanner

Reputation: 2444

Append to an existing groovy.util.Node with groovy.xml.MarkupBuilder syntax?

I'm working with an API that returns a groovy.util.Node, allowing me to customize its generated XML. I need to append a child element into the Node, and I'm wondering if I can use MarkupBuilder syntax to modify the Node.

For example, here's something that works, but seems klunky:

withXml { rootNode ->
    def appendedNode = new Node(rootNode, 'foo', [name:'bar'])
    def appendedNodeChild = new Node(appendedNode, 'child', [blah:'baz'])
}

Is there a way to append to the rootNode using MarkupBuilder-ish syntax? Thanks.

Upvotes: 5

Views: 8080

Answers (3)

btpka3
btpka3

Reputation: 3830

Checkout groovy.util.Node's javadoc, and found two methods taken 'Closure' as parameter:

  • void plus(Closure c)
  • Node replaceNode(Closure c)

So, you can do something with them. Here is a spring boot project's build.gradle sample code :

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java

            pom.withXml {
                ((groovy.util.Node) asNode()).children().first() + {
                    setResolveStrategy(Closure.DELEGATE_FIRST)
                    parent {
                        groupId 'org.springframework.boot'
                        artifactId 'spring-boot-starter-parent'
                        version "${springBootVersion}"
                    }
                    description 'A demonstration of maven POM customization'
                }
            }
        }
    }
}

Upvotes: 1

Rolf Suurd
Rolf Suurd

Reputation: 31

You can use groovy.util.Node's appendNode method:

withXml { rootNode ->
    rootNode.appendNode ('foo', [name: 'bar']).appendNode ('child', [blah: 'baz'])
}

The above code snippet will add add

<foo name="bar">
    <child blah="baz"/>
</foo>

to the rootNode.

Upvotes: 3

Aaron Saunders
Aaron Saunders

Reputation: 33345

new MarkupBuilder().root {
   foo( name:'bar' ) {
     child( blah:'blaz' )
   }
 }

don't know if I understand you question completely, but I believe you can do something like what is above

also this example from the documentation shows how you can use yield to add in additional content

http://groovy.codehaus.org/api/groovy/xml/MarkupBuilder.html

Upvotes: 0

Related Questions