on 2021 Mar 02 10:54 AM
I want to covert the following body into a hashap.
<root>
<person>
<id>0001</id>
<firstname>Jack</firstname>
<lastname>Sparrow</lastname>
</person>
<person>
<id>0002</id>
<firstname>Tony</firstname>
<lastname>Stark</lastname>
</person>
</root>
What are the changes I should be making to the following code?
def Message processData(Message message) {
def body = message.getBody(java.io.Reader);
HashMap<Integer, String> hmap = new HashMap<Integer, String>(); -----> should it be <string , string>??
def Root = new XmlSlurper().parse(body);
Root.person.each{
try{
hmap.put(it.id.text().toString(), it.firstname.text().toString(), it.lastname.text().toString());
}
catch(Exception ex){
//put relevant exception handling here
}
Thanks in advance.
Vivek.
Request clarification before answering.
Hi Vivek
You pretty much have the pieces you need in the code included in your question.
The core of it should be something like the following:
def people = [:] // Create an empty map
def root = new XmlSlurper().parseText(message.getBody(String)) // Parse the payload
// Now iterate over each <person> element
root.person.each { p ->
people[p.id.text()] = [firstname: p.firstname.text(), lastname: p.lastname.text()]
}Here's an article about working with hashmaps in Groovy.
Don't copy random code from strangers on the Internet into your solution without reading and understanding it first 🙂 So please take the time to study it and make it work in your particular iflow.
Regards and have a nice weekend,
Morten
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Vivek
A hashmap maps a key to a value, but you are trying to map a key to two values. To do this, create a hashmap, where the key is your ID and the value is another hashmap, mapping the string "firstname" to "Jack" and the string "lastname" to "Sparrow" and so on for all <person> elements.
Regards,
Morten
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
| User | Count |
|---|---|
| 13 | |
| 9 | |
| 7 | |
| 5 | |
| 4 | |
| 3 | |
| 2 | |
| 2 | |
| 2 | |
| 2 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.