2017-11-11 19 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は、well-formed 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

それを試すことができ、データがハードコード思わworks.However Rao..theコードは必ずおかげで..私たちは、動的にマップを定義することができます?別の方法がありますか? –

+0

@SantanuGhosh、答えで述べたようにデータ構造を読み込んで作成することができます。ちなみに、それはxmlを作成し、データをループする方法を示すことでした。あなたの問題を解決するなら、あなたはそれを[回答](https://stackoverflow.com/tour)として受け入れることができれば幸いです。 – Rao

+0

このような動的要素のマップのリストを作成するように私に教えてください。 –