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>
source share