If we distinguish between configure and using the Meta Object Protocol (MOP), then we can state that it is not possible to configure XmlSlurper as you describe, but it is possible to use the MOP.
For configure, note the following:
def node = new XmlSlurper().parseText('<car>No Owner</car>' )
def attr = node.@owner
assert groovy.util.slurpersupport.Attributes == attr.getClass()
If you look at the code for Attributes.text()
(in this case, Groovy 2.2.2), it is clear that this cannot be configured to return null.
For MOP, we can capture the original Attributes.text()
method and then override it:
import groovy.util.slurpersupport.*
def originalText = Attributes.metaClass.getMetaMethod("text")
Attributes.metaClass.text = { ->
def result = originalText.invoke(delegate)
if (result.isEmpty()) {
result = null
}
result
}
// no owner
def node = new XmlSlurper().parseText('<car>No Owner</car>')
def attr = node.@owner
assert null == attr.text()
// with owner
node = new XmlSlurper().parseText('<car owner="codetojoy"></car>')
attr = node.@owner
assert "codetojoy" == attr.text()