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

问题描述

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

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

如果空,我想要 bar 。我在到 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省略空属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 14:13