0

I have a problem with finding a good method to handle a xml in a way of finding some nodes in between other nodes. Example:

String test = '''
<Library>
 <Books>
  <Book>
    <Title>Hello</Title>
    <Author>John Doe</Author>
    <Publication>2008</Publication>
  </Book>
  <Book>
    <Title>Bye</Title>
    <Author>Mary Derp</Author>
    <Publication>2011</Publication>
  </Book>
  [...]
 </Books>
</Library>'''

def xml = new XmlSlurper().parseText(test)

Now I want to know if there is any book where the title is "Bye" and the author is "Mary Derp". The first thing that comes to mind is the find-method but that looks for any appearence of "Bye" and "Mary Derp".

So for example the method should look for the title "Hello" and the author "Mary Derp" and it should say false because there is no book with this title and author.

Opal
  • 81,889
  • 28
  • 189
  • 210
Justin Holze
  • 181
  • 1
  • 2
  • 11

2 Answers2

0

Here it's how it goes:

import groovy.util.XmlSlurper

String input = '''
<Library>
 <Books>
  <Book>
    <Title>Hello</Title>
    <Author>John Doe</Author>
    <Publication>2008</Publication>
  </Book>
  <Book>
    <Title>Bye</Title>
    <Author>Mary Derp</Author>
    <Publication>2011</Publication>
  </Book>
  [...]
 </Books>
</Library>'''

def slurped = new XmlSlurper().parseText(input)
assert slurped.Books.Book.find { it.Title == 'Bye' && it.Author == 'Mary Derp' }.size() == 1
assert slurped.Books.Book.find { it.Title == 'Hello' && it.Author == 'Mary Derp' }.size() == 0

find looks for any appearance of searched valued but in particular node.

Opal
  • 81,889
  • 28
  • 189
  • 210
0

You can use something like:

boolean isBookPresent(Object xml, String title, String author) {
    def myBook = xml.depthFirst().findAll { it.Title == title && it.Author == author}
    return myBook.size() > 0
}

Demo:

JMeter Groovy Check XML Presence

However if your target is to fail the sampler if the book with title of Bye by Mary Derp is not present in the response the easier way would be going for XPath Assertion like:

  1. Add XPath Assertion as a child of the request which returns the above XML
  2. Put the following expression into the "XPath Assertion" area:

    //Book[Title='Bye' and Author='Mary Derp']
    

    JMeter XPath Assertion

    If response will not contain the book you're looking for - JMeter will mark sampler as failed

    JMeter xpath assertion demo

See How to Use JMeter Assertions in Three Easy Steps article for more information on conditionally setting JMeter samplers results via assertions.

Dmitri T
  • 159,985
  • 5
  • 83
  • 133