如何制作“StringWriter MarkupBuilder”

时间:2012-05-19 13:12:05

标签: groovy

如何创建一个MarkupBuilder但具有默认构造函数的类型,该构造函数使用StringWriter初始化并覆盖toString()以调用toString() StringWriter 1}}?

这个想法如下,但当然不允许在超级构造函数调用之前初始化实例变量:

class StringWriterMarkupBuilder extends MarkupBuilder {
    final def sw = new StringWriter()
    StringWriterMarkupBuilder() {
        super(sw)
    }

    @Override String toString() {
        sw.toString()
    }
}

2 个答案:

答案 0 :(得分:2)

抱歉,我终于通过深入研究MarkupBuilder的Groovy源代码找到了解决方案!:

class StringWriterMarkupBuilder extends MarkupBuilder {
    StringWriterMarkupBuilder() {
        //MarkupBuilder.this(new IndentPrinter(new PrintWriter(writer)))
        super(new StringWriter()) 
    }

    @Override String toString() {
        //IndentPrinter.PrintWriter.StringWriter
        return super.getPrinter().out.out.toString()
    }
}

答案 1 :(得分:1)

你也可以使用metaClass这样做:

import groovy.xml.MarkupBuilder

MarkupBuilder createSWMB() {
  new StringWriter().with { sw ->
    new MarkupBuilder( sw ).with { mb ->
      mb.metaClass.toString = { -> sw.toString() }
      mb
    } 
  }
}

MarkupBuilder mb = createSWMB()
mb.root {
  names {
    name( first:'tim', second:'yates' )
  }
}
println mb.toString()