Order xml superclass elements in Java serialization

I have ParentClass and ChildClass classes in JAVA using JAXB. ChildClass extends ParentClass. When I serialize a ChildClass object, the ParentClass properties first appear in the resulting XML, first I would like to have the ChildClass properties, and then the ParentClass properties.

Is it possible?

thanks

+6
java xml-serialization jaxb
source share
1 answer

The reason JAXB is to match inheritance in an XML schema. However, you can do something like the following:

  • Mark parent @XmlTransient
  • Set propOrder in child class

Parent

import javax.xml.bind.annotation.XmlTransient; @XmlTransient public abstract class Parent { private String parentProp; public String getParentProp() { return parentProp; } public void setParentProp(String parentProp) { this.parentProp = parentProp; } } 

Child

 import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement @XmlType(propOrder={"childProp", "parentProp"}) public class Child extends Parent { private String childProp; public String getChildProp() { return childProp; } public void setChildProp(String childProp) { this.childProp = childProp; } } 

Demo

 import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Child.class); Child child = new Child(); child.setParentProp("parent-value"); child.setChildProp("child-value"); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(child, System.out); } } 

Exit

 <child> <childProp>child-value</childProp> <parentProp>parent-value</parentProp> </child> 
+9
source share

All Articles