wybourn
wybourn

Reputation: 678

How do you add an attribute and node value when creating xml in groovy

I'm using to groovy to create a dynamic XML document where each node can contain a value, attributes, or both.

For example

<root>
  <a id="123"> someValue </a>
<root>

I can't seem to find an example of where a node is created with both a value and a set of attributes.

Here's the line of code that creates a node (inside other code that creates the XML document and root element)

// node is a map, as is node.attributes
"${node.node_name}"(node.attributes.each { k, v -> "${k}:${v}"})

creates the following:

<a id=123 />

whereas:

"${node.node_name}""${node.value}"

creates:

<a>someValue <a>

What code would create a node with both the attribute and value set, looking like this:

<a id=123> someValue </a>

Any help is appreciated.

Upvotes: 1

Views: 3150

Answers (1)

Opal
Opal

Reputation: 84766

Here's the code you're looking for:

import groovy.xml.MarkupBuilder

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

xml.root() {
    a(id: 123, 'someValue')
}
println writer.toString()

Upvotes: 2

Related Questions