Groovy AntBuilder, omit conditional attributes, like “setOmitNullAttributes” functionality on MarkupBulder

混江龙づ霸主 提交于 2019-12-10 11:56:18

问题


sample code:

def ant = new AntBuilder()
ant.'antlib:org.jacoco.ant:agent'(
                enabled: enabled,
                property: 'agentvmparam')

When that "enabled" parameter is null, I'd like it to be not present in the ant task conversion, not merely "empty". "empty" gets evaluated to "true" http://ant.apache.org/manual/develop.html#set-magic which isn't what I want.

xml builder example:

def xml = new MarkupBuilder()
xml.omitNullAttributes = true
xml.root(
        requiredAttribute:'required',
        optionalAttribute: optionalAttribute
        ) { }

That "omitNullAttributes" will ensure that the "optionalAttribute" xml element parameter isn't even present if the Groovy parameter evaluates to null.

so I get

<root requiredAttribute='required' />

instead of

<root requiredAttribute='required' optionalAttribute='' />

回答1:


Bit of a possible workaround, but does this work?

def ant = new AntBuilder()
ant.'antlib:org.jacoco.ant:agent'( [ enabled:enabled, 
                                     property:'agentvmparam' ].findAll { it.value != null } )

ie: use a findAll to remove the null entries of the param map



来源:https://stackoverflow.com/questions/4692087/groovy-antbuilder-omit-conditional-attributes-like-setomitnullattributes-fun

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