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
精彩评论