Adding dynamic elements and attributes to groovy MarkupBuilder or StreamingMarkupBuilder [closed]

StackOverflow https://stackoverflow.com/questions/12789738

  •  06-07-2021
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top