Finally I found the reason by loooking at the Groovy's groovy.util.slurpersupport.GPathResult class source code. The groovy.util.XmlSlurper().parseText() method returns a descendant of GPathResult and even doc.elm is a GPathResult.
This class uses a special meta class that permits to change the behavior of the .@ operator.
Suppose you have a Test class:
class Test {
}
this script
def t = new Test()
println t.@attr
fails by a "groovy.lang.MissingFieldException: No such field: attr for class: Test", unless you have a field "attr" defined in the Test class.
Following the example of GPathResult, you can change this behavior by defining a custom meta class:
MetaClass newMetaClass = new DelegatingMetaClass(metaClass) {
@Override
public Object getAttribute(Object object, String attribute) {
"my$attribute"
}
}
def t = new Test()
t.metaClass = newMetaClass
println t.@hello
Now, there is no error, and "myhello" is displayed!
Bertrand.
bgoetzmann wrote
Hello,
I ask me a simple question about the use of the .@ operation for accessing a XML attribute.
Here a simple example of parsing a XML document using XmlSlurper class:
def xml = '''
<test>
<elm att="attr">elm</elm>
</test>
'''
def doc = new groovy.util.XmlSlurper().parseText(xml)
println doc.elm.@att // displays 'attr'
In this example, we can use the .@ operator, normally used to access directly to a class attribute, to get the attribute value.
So, my question is: why does it work, and how?
Thank you.
Bertrand.