title: Adding multiple XML elements/containers dynamically using XML MarkupBuilder in Groovy
body: <p>I am trying to generate XML using Groovy MarkupBuilder.</p>
  
  <p>XML needed is of this form (simplified):</p>
  
  <pre><code>&lt;Order&gt;
    &lt;StoreID /&gt;
    &lt;City /&gt;
    &lt;Items&gt;
      &lt;Item&gt;
        &lt;ItemCode /&gt;
        &lt;UnitPrice /&gt;
        &lt;Quantity /&gt;
      &lt;/Item&gt;
    &lt;/Items&gt;
  &lt;/Order&gt;
  </code></pre>
  
  <p>The data is stored in an Excel file and is easily accessible. My Groovy script parses the Excel and generates the XML. </p>
  
  <p>e.g.</p>
  
  <pre><code>import groovy.xml.*
  def writer = new StringWriter()
  def xml = new MarkupBuilder(writer)
  
  xml.Order{
    StoreID("Store1")
    City("New York")
    Items(){
      Item(){
        ItemCode("LED_TV")
        UnitPrice("800.00")
        Quantity("2")
      }
    }
  }
  </code></pre>
  
  <p>There can be multiple "item" containers inside "items".</p>
  
  <p>My question is: 
  Let's say we want to generate Order XML having 10 items. Is there a way to write something like a for loop inside "items" container? That way, we won't need to write MarkupBuilder code for 10 different items.</p>
  
  <p>There is a similar question <a href="https://stackoverflow.com/questions/12789738/adding-dynamic-elements-and-attributes-to-groovy-markupbuilder-or-streamingmarku">Adding dynamic elements and attributes to groovy MarkupBuilder or StreamingMarkupBuilder</a>. But it doesn't discuss looping.</p>