Combining multiple fragments of JAXB elements into a single root node?

I am now figuring out JAXB and I am very close to what I need. Currently, my ArrayList is populated from a DB query and then sorted into a file, but the problem is that my marshalling objects are not wrapped in the root directory of the node. How can i do this?

try //Java reflection { Class<?> myClass = Class.forName(command); // get the class named after their input JAXBContext jaxbContext = JAXBContext.newInstance(myClass); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); ArrayList<JAXBElement> listOfJAXBElements = getJAXBElementList(myClass); FileOutputStream fileOutput = new FileOutputStream(command + ".xml", true); for(JAXBElement currentElement: listOfJAXBElements) { marshaller.marshal(currentElement, fileOutput); } fileOutput.close(); } catch (IOException | NullPointerException | ClassNotFoundException| JAXBException| SecurityException | IllegalArgumentException e) { } 

Here's the account class:

 @XmlRootElement(name="accounts") @Entity @Table(name="Account") public class account implements Serializable { ... } 

Here is my conclusion:

 <class account> <accountNumber>A101</accountNumber> <balance>500.0</balance> <branchName>Downtown</branchName> </class account> <class account> <accountNumber>A102</accountNumber> <balance>400.0</balance> <branchName>Perryridge</branchName> </class account> 

I would like to:

 <accounts> <class account> <accountNumber>A101</accountNumber> <balance>500.0</balance> <branchName>Downtown</branchName> </class account> <class account> <accountNumber>A102</accountNumber> <balance>400.0</balance> <branchName>Perryridge</branchName> </class account> </accounts> 

EDIT 1: sorting objects in turn produces:

 <accounts> <accountNumber>A101</accountNumber> <balance>500.0</balance> <branchName>Downtown</branchName> </accounts> <accounts> <accountNumber>A102</accountNumber> <balance>400.0</balance> <branchName>Perryridge</branchName> </accounts> 
+4
source share
2 answers

You can do exactly what you are doing now, and also write <accounts> to FileOutputStream before you marshal objects and </accounts> after.

You can also enter a new domain object to store the list.

 @XmlRootElememnt @XmlAccessorType(XmlAccessType.FIELD) public class Accounts { @XmlElement(name="account") List<Account> accounts; } 
+1
source

Use @XmlElementWrapper(name = "accounts")

More on XMLElementWrapper annotation

How to use it:

  @XmlElementWrapper(name = "bookList") // XmlElement sets the name of the entities @XmlElement(name = "book") private ArrayList<Book> bookList; 
+2
source

All Articles