xmlgroovymarkupbuilder

Adding dynamic elements and attributes to groovy MarkupBuilder or StreamingMarkupBuilder


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.


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>