Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip the null fields during jaxb marshalling

Is there a way for marshaller to generate a new xml file skipping any null attributes? So something like someAttribute="" does not show up in the file.

Thanks

like image 365
user2167013 Avatar asked Oct 19 '25 10:10

user2167013


1 Answers

A JAXB (JSR-222) implementation will not marshal a field/property annotated with @XmlAttribute that contains a null value.

Java Model (Root)

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Root {

    private String foo;
    private String bar;

    @XmlAttribute
    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    @XmlAttribute(required=true)
    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}

Demo Code

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Root root = new Root();
        root.setFoo(null);
        root.setBar(null);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

Output

<?xml version="1.0" encoding="UTF-8"?>
<root/>
like image 183
bdoughan Avatar answered Oct 22 '25 05:10

bdoughan