Omit empty attributes with groovy DOMBuilder

偶尔善良 提交于 2019-12-10 22:58:37

问题


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 remove them. Since I have a complex DOM to be generated, I'm looking for other options.


回答1:


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"/>


来源:https://stackoverflow.com/questions/5032827/omit-empty-attributes-with-groovy-dombuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!