使用groovy DOMBuilder省略空属性 [英] Omit empty attributes with groovy DOMBuilder

查看:159
本文介绍了使用groovy DOMBuilder省略空属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Groovy的 MarkupBuilder 有一个 omitNullAttributes omitEmptyAttributes 。但 DOMBuilder 没有。这是我的代码

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

如果空,我想要 bar 。我在 Groovy AntBuilder的答案中找到了解决方法,省略了条件属性.. 。 findAll 空属性并删除它们。因为我有一个复杂的DOM生成,我正在寻找其他选项。

解决方案

我相信没有内置的,在该选项中,但如果您需要一个DOMBuilder,您可以将其子类化并过滤属性...

  @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}
}
}

您可能想按照标准DOMBuilder调整构造,这只是一个例子。

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

标准输出,如你所说...



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


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.

解决方案

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

这篇关于使用groovy DOMBuilder省略空属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆