I have some objects let's say two, A and B. These objects from the same class. I need to marshal these objects using JAXB and the output XML should be in this form:
<Root>
<A>
<ID> an id </ID>
</A>
<B>
<ID> an id </ID>
</B>
</Root>
<!-- Then all A and B attributes must be listed !-->
<A>
<ID> an id </ID>
<attribute1> value </attribute1>
<attribute2> value </attribute2>
</A>
<B>
<ID> an id </ID>
<attribute1> value </attribute1>
<attribute2> value </attribute2>
</B>
How to generate this format in JAXB? Any help is appreciated.
Update: To be more specific, Assume we have Human class like this:
@XmlRootElement
public class Human {
private String name;
private int age;
private Integer nationalID;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Integer getNationalID() {
return nationalID;
}
public void setNationalID(Integer nationalID) {
this.nationalID = nationalID;
}
}
and our main class is:
public class Main3 {
public static void main(String[] args) throws JAXBException {
Human human1 = new Human();
human1.setName("John");
human1.setAge(24);
human1.setNationalID(Integer.valueOf(123456789));
JAXBContext context = JAXBContext.newInstance(Human.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
StringWriter stringWriter = new StringWriter();
m.marshal(human1, stringWriter);
System.out.println(stringWriter.toString());
}
}
Then the output will be:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<human>
<age>24</age>
<name>John</name>
<nationalID>123456789</nationalID>
</human>
Now I need the output to be like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<human>
<nationalID>123456789</nationalID>
</human>
<human>
<nationalID>123456789</nationalID>
<age>24</age>
<name>John</name>
</human>
And this will help me draw a tree of XML objects without the attributes (only by ID) and then but all the definitions below the tree. Is this possible using JAXB or any other implementation?
The output will be
Try this: