Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify that JAXB should only print an attribute if it doesn't have a specific value?

Tags:

java

xml

jaxb

I am working with JAXB to marshal and unmarshal a java class.

This is the xml I'm looking for:

<tag name="example" attribute1="enumValue"/>

if attribute1 is set to the default value, I don't want that attribute to print at all, so it would look like this:

<tag name="example"/>

Is there a way to do this?

Right now I have a getter/setter pair that looks like this:

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

public void setEnumExample(final EnumExample enumExample) {
    this.enumExample = enumExample;
}
like image 253
chama Avatar asked Feb 16 '23 07:02

chama


1 Answers

Tag

You could leverage the fact that JAXB will not marshal null attribute values and add some logic to your properties and then use JAXB to map to the field.

import javax.xml.bind.annotation.*;

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

    private static Foo ATTRIBUTE1_DEFAULT = Foo.A;

    enum Foo {A, B};

    @XmlAttribute
    private Foo attribute1;

    public Foo getAttribute1() {
        if(null == attribute1) {
            return ATTRIBUTE1_DEFAULT;
        }
        return attribute1;
    }

    public void setAttribute1(Foo attribute1) {
        if(ATTRIBUTE1_DEFAULT == attribute1) {
            this.attribute1 = null;
        } else {
            this.attribute1 = attribute1;
        }
    }

}

Demo

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);
    }

}

Output

A
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tag/>
B
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tag attribute1="B"/>
like image 91
bdoughan Avatar answered Apr 26 '23 19:04

bdoughan