OTUser
OTUser

Reputation: 3848

Create a Map with specific parent node value and all of its child node values of an XML

I have a sample LEDES XML file https://codebeautify.org/xmlviewer/cbdc79e7 and I am trying to create a Map with Invoice node's inv_id value as key and all of its child elements file_item_nbr values as below

['Invoice 31' : [10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33] 
 'Invoice 32' : [50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73] 
]

can someone please help me with it?

Upvotes: 0

Views: 696

Answers (1)

Rao
Rao

Reputation: 21369

You should be able to get it with sudo code:

  • Use XmlSlurper to parse xml
  • Read all invoice elements
  • Build the required map

Here is the script:

//Not putting entire xml here, just pass the xml as string to parseText method
def xml = new XmlSlurper().parseText(xmlString)
//Get the invoices
def invoices = xml.'**'.findAll{it.name() == 'invoice'}
//Build the desired result
println invoices.collectEntries {inv -> [(inv.inv_id): inv.'**'.findAll{it.name() == 'file_item_nbr'}*.text()] }

You may quickly try it online demo

Upvotes: 1

Related Questions