开发者

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

开发者 https://www.devze.com 2023-01-11 13:07 出处:网络
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 synta

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 th开发者_开发百科e 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.


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.


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'
                }
            }
        }
    }
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消