'How to get xml elements by child element in karate?

I am trying to get xml elements by child element in karate, as following:

<tasks>
 <task>
   <Id>S1</Id>
   <UID>1</UID>                  
 </task>
 <task>
   <Id>S2</Id>
   <UID>2</UID>                  
 </task>
</tasks>

From the above xml example, I want to get elements of 'task' tag having Id='S2' using karate. My expected result after getting:

 <task>
   <Id>S2</Id>
   <UID>2</UID>                  
 </task>

So please help me if you know that how to get xml elements by child element in karate? Thanks!



Solution 1:[1]

My suggestion is to convert the XML to JSON. This makes a lot of data-operations easier:

* def response =
"""
<tasks>
 <task>
   <Id>S1</Id>
   <UID>1</UID>                  
 </task>
 <task>
   <Id>S2</Id>
   <UID>2</UID>                  
 </task>
</tasks>
"""
* json response = response
* def found = response.tasks.task.find(x => x.Id == 'S2')
* match found == { Id: 'S2', UID: '2' }

Once you have data in JSON, refer the docs for other transforms you can do: https://github.com/karatelabs/karate#json-transforms

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Thomas