1
import groovy.xml.MarkupBuilder
class Foo {
    Foo() {}
    String boo() {
        def writer = new StringWriter()
        def xml = new MarkupBuilder(writer)
        xml.records() {
            car(name:'HSV Maloo', make:'Holden', year:2006) {
                country('Australia')
                record(type:'speed', 'Production Pickup Truck with speed of 271kph')
            }
        }
        println writer
    }
    def methodMissing(String methodName, args) {
        println "Get called"
    }
}

Foo a = new Foo()
a.boo()

结果:

Get called
<records />

不执行methodMissing(),结果:

<records>
  <car name='HSV Maloo' make='Holden' year='2006'>
    <country>Australia</country>
    <record type='speed'>Production Pickup Truck with speed of 271kph</record>
  </car>
</records>

我现在正在挠头流血,我在这里错过了什么?

4

1 回答 1

1

问题是当boo()被调用时,它会创建一个MarkupBuilder并最终命中:

        car(name:'HSV Maloo', make:'Holden', year:2006) {

这将检查car您的类中的方法,如果未找到,则在closure(MarkupBuilder)的委托中检查方法。MarkupBuilder 捕捉到这一点,并生成一个 xml 节点。

但是,您已经定义methodMissing了 ,因此当它检查您的类中的car方法时,它会找到一个并使用它(什么都不做)

要解决此问题,您可以通过调用xml.car()xml.country()等来明确要求使用 MarkupBuilder:

String boo() {
    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer)
    xml.records() {
        xml.car(name:'HSV Maloo', make:'Holden', year:2006) {
            xml.country('Australia')
            xml.record(type:'speed', 'Production Pickup Truck with speed of 271kph')
        }
    }
    println writer
}
于 2013-09-05T09:38:38.947 回答