Извините, ваш подход не совпадает с Groovy, невозможно применить строку запроса XPATH непосредственно к результату XmlParser.
Прелесть обработки XML в groovy заключается в том, что вы получаете действительно мощный набор инструментов. Применение их к вашему вопросу дает:
def var = 'number'
def nodeName = 'childNode'
// get all numbers on childNode
myTest."$nodeName"."@$var"
// set just a selected number to 48
// the key for the search could also be a variable
myTest."${nodeName}".find { it.@name == "toto"}."@$var" = 48
// set all numbers to 48
myTest."${nodeName}".each { it."@$var" = 48 }
// set all names to something else
var = "name"
myTest."${nodeName}".each { it."@$var" = "something else" }
Проверьте отличную документацию обработки XML с groovy на
http://groovy -lang.org / обработка-xml.html .
Если вы все еще заинтересованы в использовании полной строки запроса XPath, попробуйте следующее:
def setValue(xml, xpathQuery, value) {
// parse xml
def data = new XmlParser(false, true).parseText(xml)
// split query string
def fullPath = xpathQuery.split('\\.')
// prepare query attributes for first recursion and start
def attribute = fullPath.head(), path = fullPath.tail()
recursiveSetValue(data, attribute, path, value)
// for demonstration only
XmlUtil.serialize(data)
}
def recursiveSetValue(node, attribute, path, value) {
// in case of a list of nodes branch out
if(node instanceof NodeList) {
node.each {
recursiveSetValue(it, attribute, path, value)
}
// no more elements in path, so this is the element to be set;
// do it and return
} else if (path == []) {
node[attribute] = value
// continue searching for the matching node on the next level
} else {
recursiveSetValue(node[attribute], path.head(), path.tail(), value)
}
}
def xml = myTest // from your example
// I prefer to leave the @ with number as it directs to the
// attribute of the XML node instead of a new node
def var = "@number"
def path = "childNode." + var
def value = 43
setValue (xml, path, value)