How to skip the null fields during jaxb marshalling
13,923
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/>
Related videos on Youtube
Author by
user2167013
Updated on September 15, 2022Comments
-
user2167013 over 1 year
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
-
user2167013 over 10 yearsThank you so much for your answer. However, I checked my jaxb version lnx-davidw:/export/home/davidw/JavaProj/xsd 1837=> xjc -version xjc version "JAXB 2.1.10" JavaTM Architecture for XML Binding(JAXB) Reference Implementation, (build JAXB 2.1.10) lnx-davidw:/export/home/davidw/JavaProj/xsd 1839=> /usr/bin/java -version java version "1.6.0_22" OpenJDK Runtime Environment (IcedTea6 1.10.4) (rhel-1.24.1.10.4.el5-x86_64) OpenJDK 64-Bit Server VM (build 20.0-b11, mixed mode) lnx-davidw:/export/home/davidw/JavaProj/xsd 1840=> /usr/bin/javac -version javac 1.6.0_22 I should have that, should I?
-
bdoughan over 10 years@user2167013 - The behaviour I described should be the same for all JAXB versions an implementations. Are you sure your value is null and not
""
.