【问题标题】:Groovy xml dynamic codingGroovy xml动态编码
【发布时间】:2017-11-11 06:25:09
【问题描述】:

我希望使用来自用户的输入(比如发票列表)创建一个动态 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>

【问题讨论】:

    标签: xml groovy streamingmarkupbuilder


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

    关注在线 cmets。

    给你:

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

    【讨论】:

    • 谢谢Rao..代码确实有效。但是数据似乎是硬编码的..我们可以动态定义地图吗?还有其他方法吗?
    • @SantanuGhosh,您可以阅读并创建答案中提到的数据结构。顺便说一句,那是为了表明您可以创建 xml 以及如何循环遍历数据。如果可以解决您的问题,您是否可以接受 answered 表示感谢。
    • 能否指导我创建此类动态元素的地图列表。
    • 您可以在data对象中看到地图列表。
    猜你喜欢
    • 2022-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多