Reputation: 359
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
Upvotes: 4
Views: 18930
Reputation: 149057
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/>
Upvotes: 7