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>
StreamingMarkupBuilder
to create the xml.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