-4

I wish to create a dynamic XML file using inputs from the user(say an invoice list). As an input the Groovy script taken in number of items and based on the user entry, inputs the attributes per Invoice. Could you please guide me on the block of code where i should apply looping logic?

Sample:-

Enter the total number of invoices: 
3
Enter the invoice 1 details:
26354
15000
17-12-2017
Harry
Enter the invoice 2 details:
16514
28000
24-09-2017
James

Expected output:-

<invoices>
<invoice number='26354'>
<price>15000.0</price>
<date>17-17-2017</date>
<customer>Clinton</customer>
</invoice>
<invoice number='16514'>
<price>28000.0</price>
<date>24-08-2017</date>
<customer>Mark</customer>
</invoice>
</invoices>
Rao
  • 20,781
  • 11
  • 57
  • 77

1 Answers1

1
  • You can define your data as list of maps.
  • Use StreamingMarkupBuilder to create the xml.
  • You haven't mentioned the root element name, and invoiceRequest is used as sample to make it well-formed xml, change its name as needed.

Follow in-line comments.

Here you go:

//Define your data as list of maps as shown below
def data = [ 
             [number: 26354, price: 15000, date: '17-12-2017', customer: 'Clinton'],
         [number: 16514, price: 28000, date: '24-08-2017', customer: 'Mark']
           ]

def xml = new groovy.xml.StreamingMarkupBuilder().bind {
    //Change the root element as needed instead of invoiceRequest
    invoiceRequest {
    invoices {
           //Loop thru list and create invoice elements
           data.each { inv ->
              invoice (number: inv.number) {
                 price (inv.price as double)
                 date (inv.date)
                 customer(inv.customer)
              }
           }
        }
    }
}
println groovy.xml.XmlUtil.serialize(xml)

You can try it on-line demo quickly

Rao
  • 20,781
  • 11
  • 57
  • 77
  • Thanks Rao..the code sure works.However the data seems hardcoded.. can we define Maps dynamically?Is there any alternate way? – Santanu Ghosh Nov 11 '17 at 08:34
  • @SantanuGhosh, You can read and create data structure as mentioned in the answer. By the way, that was to show you can create xml & how you loop thru the data. Appreciate if you can accept it as [answered](https://stackoverflow.com/tour) if that solves your problem. – Rao Nov 11 '17 at 09:49
  • Could please guide me to create a list of maps of such dynamic elements. – Santanu Ghosh Nov 11 '17 at 11:21
  • You could see the list of maps in `data` object. – Rao Nov 11 '17 at 12:05