XML > JAXB > Serialize data to XML Tag attributes2
Serialize data to XML Tag attributes2
The following example shows serializing a POJO to an XML.
The POJO should have a no-arg default constructor and
@XmlRootElement annotation at class level.
The annotation @XmlAttribute serializes data as tag attribute.
JAXB uses the following accessor types to serialize java object to XML,
PUBLIC_MEMBER (default) - Binds public getters/setters/fields
FIELD - Binds non static, non transient fields
PROPERTY - Binds public getters/setters
NONE - No binding
As the default accessor type is PUBLIC_MEMBER, the annotation(Such as @XmlAttribute) we put at
field level causes Class has two properties of the same name exception.
This is because JAXB tries to get data using both fields and getter/setter pairs.
We can solve this problem by placing annotation at public getter/setter level using default PUBLIC_MEMBER accessor type.
The other way is to place annotations at field level by specifying FIELD accessor type.
The below example uses the default PUBLIC_MEMBER accessor type.
public static void main (String [] args) throws JAXBException {
Student8 student = new Student8("Sriram", "Kasireddi", 2, "Painting", new Date());
/**
* Create JAXB Context from the classes to be serialized
*/
JAXBContext context = JAXBContext.newInstance(Student8.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(student, System.out);