I am trying to marshall the inputs using JAXB annotations and I am facing some small issues. Wanted to confirm if it's possible to achieve
I have two classes parent
and child
each of which has many fields. child
class extends parent
class.
Is it possible to add the elements from parent
class in the child
class prepOrder
for @XmlType
?
Is it necessary to add all elements within the propOrder
? for example if I have 10 fields out of which I want only 4 fields to be ordered. Rest can appear in any order they want. Is it possible to do this? Because when I do not add a field then I am getting the error.
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Parent",propOrder={"city","year"})
public class Parent{
private String brand;
private String city;
private String year;
//Getters and Setters avoided
}
@XmlRootElement(name = "Car")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Child",propOrder={"engine","brand","build"})
public class Child{
private String engine;
private String build;
//Getter and Setters avoided
}
public class Main{
public static void main(String []args){
Child child = new Child();
//Adding values and creating xml using the Marshalling approach
JAXBContext context = JAXBContext.newInstance(Child.class);
Marshaller mar = context.createMarshaller();
mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
mar.marshal(child, System.out);
}
}
The final xml that I am looking forward to is:
<?xml version="1.0"?>
<child>
<cit>Frankfurt</cit>
<year>2021</year>
<engine>Mercedes</engine>
<brand>Ferari</brand>
<build>Germany</build>
</child>
After a lot of trial and error methods, I was able to do it. Posting the answer as it can be useful to someone else in the future:
@XmlTransient
annotation on the Parent
class and remove the propOrder
.@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Parent")
@XmlTransient
public class Parent{
//All the parent element fields and other codes getter/setters
}
Child
class which is extending Parent
@XmlRootElement(name = "Car")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Child",propOrder={"city","year","engine","brand","build"})
public class Child{
}