-4

我希望使用来自用户的输入(比如发票列表)创建一个动态 XML 文件。作为输入,Groovy 脚本采用项目数量并基于用户输入,输入每个 Invoice 的属性。能否请您指导我应该应用循环逻辑的代码块?

样本:-

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

预期输出:-

<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>
4

1 回答 1

1
  • 您可以将数据定义为地图列表。
  • 用于StreamingMarkupBuilder创建 xml。
  • 您没有提到根元素名称,并invoiceRequest用作示例以使其格式良好的 xml,根据需要更改其名称。

关注在线评论。

干得好:

//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)

您可以demo快速在线试用

于 2017-11-11T08:23:21.973 回答