1

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!

1 Answers1

0

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

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • Thanks Peter for suggesting, it already works with JSON format and I am wanting it to work the same with xml format. Do you have any suggestions for me with xml format? – Louis Hoang Mar 20 '22 at 15:17
  • @LouisHoang it may be possible if you are an XPath expert - but I'm sorry I can't help. my personal opinion is that if you are using Karate for `testing` it shouldn't matter whether you convert it to JSON or not. if you are not doing testing Karate is the wrong tool. does that make sense ? note that it should be possible to convert JSON to XML. also please read this: https://stackoverflow.com/a/54126724/143475 – Peter Thomas Mar 20 '22 at 15:24