2017-11-11 1 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

동적 요소에 대한지도 목록을 작성하도록 안내해주십시오. –