有没有办法指定JAXB只应打印属性,如果它没有特定的值?

cha*_*ama 4 java xml jaxb

我正在使用JAXB来编组和解组java类.

这是我正在寻找的xml:

<tag name="example" attribute1="enumValue"/>
Run Code Online (Sandbox Code Playgroud)

如果attribute1设置为默认值,我不希望该属性打印,所以它看起来像这样:

<tag name="example"/>
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

现在我有一个看起来像这样的getter/setter对:

@XmlAttribute(name="attribute1")
public EnumExample getEnumExample() {
    return this.enumExample;
}

public void setEnumExample(final EnumExample enumExample) {
    this.enumExample = enumExample;
}
Run Code Online (Sandbox Code Playgroud)

bdo*_*han 5

您可以使用XmlAdapterfor这个用例:

XmlAdapter(Attribute1Adapter)

您可以利用以下事实:JAXB不会XmlAdapter封送空属性值,并使用a 来调整正在编组为XML的值.

import javax.xml.bind.annotation.adapters.XmlAdapter;
import forum16972549.Tag.Foo;

public class Attribute1Adapter extends XmlAdapter<Tag.Foo, Tag.Foo>{

    @Override
    public Foo unmarshal(Foo v) throws Exception {
        return v;
    }

    @Override
    public Foo marshal(Foo v) throws Exception {
        if(v == Foo.A) {
            return null;
        }
        return v;
    }

}
Run Code Online (Sandbox Code Playgroud)

域模型(标签)

@XmlJavaTypeAdapter注释用于关联的XmlAdapter.

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Tag {

    enum Foo {A, B};

    @XmlAttribute
    @XmlJavaTypeAdapter(Attribute1Adapter.class)
    private Foo attribute1;

    public Foo getAttribute1() {
        return attribute1;
    }

    public void setAttribute1(Foo attribute1) {
        this.attribute1 = attribute1;
    }

}
Run Code Online (Sandbox Code Playgroud)

演示

下面是一些演示代码,您可以使用它来证明一切正常.

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tag.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Tag tag = new Tag();
        tag.setAttribute1(Tag.Foo.A);
        System.out.println(tag.getAttribute1());
        marshaller.marshal(tag, System.out);

        tag.setAttribute1(Tag.Foo.B);
        System.out.println(tag.getAttribute1());
        marshaller.marshal(tag, System.out);
    }

}
Run Code Online (Sandbox Code Playgroud)

产量

以下是运行演示代码的输出.

A
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tag/>
B
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tag attribute1="B"/>
Run Code Online (Sandbox Code Playgroud)