开发者

Omit empty attributes with groovy DOMBuilder

Groovy's MarkupBuilder has an omitNullAttributes and an omitEmptyAttributes. But DOMBuilder doesn't. This is the code I have

>>> def xml = DOMBuilder.newInstance()
>>> def maybeEmpty = null
>>> println xml.foo(bar: maybeEmpty)
<foo bar=""/>

I want bar to be omitted if empty. I found a workaround in an answer to Groovy AntBuilder, omit conditional attributes... to findAll empty attributes and remo开发者_如何学Cve them. Since I have a complex DOM to be generated, I'm looking for other options.


I believe there is no built-in option for that, but if you need a DOMBuilder, you could subclass it and filter the attributes...

@groovy.transform.InheritConstructors
class DOMBuilderSubclass extends groovy.xml.DOMBuilder {
    @Override
    protected Object createNode(Object name, Map attributes) {
        super.createNode name, attributes.findAll{it.value != null}
     }
}

You might want to tune the construction as in standard DOMBuilder, this is just an example.

def factory = groovy.xml.FactorySupport.createDocumentBuilderFactory().newDocumentBuilder()
def builder = new DOMBuilderSubclass(factory)
println builder.foo(bar: null, baz: 1)
//<?xml version="1.0" encoding="UTF-8"?>
//<foo baz="1"/>    

standard output as you said was...

println groovy.xml.DOMBuilder.newInstance().foo(bar: null, baz: 1)
//<?xml version="1.0" encoding="UTF-8"?>
//<foo bar="" baz="1"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜