2017-11-11 36 views
-4

我希望使用用戶輸入(例如發票清單)創建動態XML文件。作爲一個輸入,Groovy腳本採用多個項目並基於用戶輸入,輸入每個發票的屬性。 可否請你指導我在哪裏我應該應用循環邏輯的代碼塊?Groovy xml動態編碼

樣品: -

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> 

回答

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快速

+0

感謝Rao..the代碼肯定works.However數據似乎硬編碼..我們可以動態地定義地圖?有其他方法嗎? –

+0

@SantanuGhosh,你可以閱讀和創建答案中提到的數據結構。順便說一下,這是爲了表明您可以創建xml以及如何循環數據。感謝您接受它[回答](https://stackoverflow.com/tour),如果這能解決您的問題。 – Rao

+0

可以請指導我創建這種動態元素的地圖列表。 –