I've seen many example using Groovy's MarkupBuilder
for building an XML document, but they all seem to use static attributes for every element in the document (the attribute names are all known at compile time). What if I'm trying to construct an XML document where the attribute names aren't known until runtime? I haven't yet figured out the syntax require to solve a problem like this.
Asked
Active
Viewed 6,124 times
11
-
can't you just pass a map with variable names as keys, ie: `node( [ (key): "value" ] )` – tim_yates Oct 08 '12 at 22:27
-
Yes! I was trying to do that previously, but it wasn't working for me (the map was getting added as a sub-element and not as attributes). But your response prompted me to make sure I wasn't doing it wrong and sure enough I was. I'm pretty new to groovy, and I was initially declaring my empty map as a list ([] vs [:]). Thanks for the push, tim! – pneumee Oct 08 '12 at 22:55
-
Np :-) I've written this out in full as an answer to the question :-) I wanted to check it worked as I thought first – tim_yates Oct 09 '12 at 08:36
1 Answers
7
A map with the attribute names as keys should do it. You need to wrap the key in braces so that Groovy knows you mean to use the value of a
rather than the key a
:
import groovy.xml.MarkupBuilder
new MarkupBuilder().root {
def a = 'dynAttr'
node( [ (a):'woo' ] )
}
Would generate:
<root>
<node dynAttr='woo' />
</root>

tim_yates
- 167,322
- 27
- 342
- 338
-
thanks! Just FYI, in my solution I didn't surround the key with braces and it still worked great. – pneumee Oct 09 '12 at 22:41
-