Home > Net >  use XmlPath to search and return nodes
use XmlPath to search and return nodes

Time:08-03

Is there a way to use RestAssured's "XmlPath" to return a list of nodes, rather than a list of strings? For example, let's assume I want to find every bald stooge.

import com.jayway.restassured.path.xml.XmlPath

def xml = '''
<stooges>
   <stooge name="larry">
       <hair>curly</hair>
       <tagline>I'm not sure about this...</tagline>
   </stooge>
   
   <stooge name="curly">
       <hair>bald</hair>
       <tagline>Nyuk! Nyuk! Nyuk!</tagline> 
   </stooge>
   
   <stooge name="moe">
       <hair>bowl</hair>
       <tagline>Why I oughtta...</tagline> 
   </stooge>
</stooges>
'''

def pathData = XmlPath.from(xml)

// this will run, but it gives me a single-item list of strings.  I can't navigate the tree from there
def listOfStrings = pathData.getList("stooges.stooge.**.findAll {it.name() == 'hair' && it.text() == 'bald'}")

// this fails with
// Caught: java.lang.ClassCastException: Cannot convert class java.lang.String to interface com.jayway.restassured.path.xml.element.Node
def thisWillFail = pathData.getNode("stooges.stooge.**.findAll { it.name() == 'hair' && it.text() == 'bald'}")

CodePudding user response:

@Grab(group='com.jayway.restassured', module='xml-path', version='2.9.0', transitive=false)

import com.jayway.restassured.path.xml.XmlPath

def xml = '''
...your xml here...
'''

def pathData = XmlPath.from(xml)
def list = pathData.get("stooges.stooge.findAll{it.hair.text() in ['bald','bowl']}")

list.each{println "hair=$it.hair => $it.tagline"}

prints:

hair=bald => Nyuk! Nyuk! Nyuk!
hair=bowl => Why I oughtta...
  • Related