Following is a sample XML:
<root>
<persons>
<person gender="female">X</person>
<person gender="female">Y</person>
<person gender="male">Z</person>
</persons>
</root>
I want to get the element count which has gender="male"
by using GPath.
I have following code:
def xml =
'''
<root>
<persons>
<person gender="female">X</person>
<person gender="female">Y</person>
<person gender="male">Z</person>
</persons>
</root>
'''
def slurper = new XmlSlurper()
def parsedText = slurper.parseText(xml)
def locator = 'persons.person[@gender="male"]'
def elements = Eval.x(parsedText, "x.${locator}")
println elements.size()
It is giving me error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: unexpected token: = @ line 1, column 25.
x.persons.person[@gender="male"]
^
1 error
The code is only for demonstration purpose of the problem. In the actual case, I have a utility method which accepts an XML and a GPath and returns if there is any element can be found by the given GPath.
Update: 1
Following is the actual utility method which takes xml and locator (GPath) as args and check if there is any element whose path matches the provided locator.
public static void verifyElementExists(String xml, String locator) throws NoElementFoundException {
def slurper = new XmlSlurper()
def parsedText = slurper.parseText(xml)
def elements = Eval.x(parsedText, "x.${locator}")
if(elements.size() == 0) {
throw new NoElementFoundException()
}
}