Writing and adding each item to the line ends. Is there a way to get the JAXB marshaller to sort the list of objects where I can just give it the name of the top element?
It seems to me that I'm close with this
public <T> String jaxb(Collection<T> o, Class<T> clazz, String plural){
try {
ArrayList<T> al = new ArrayList<T>(o.size());
al.addAll(o);
JAXBContext jc = JAXBContext.newInstance(ArrayList.class);
JAXBElement<ArrayList> amenity = new JAXBElement(new QName(plural), ArrayList.class, al);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(amenity, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
but the result still returns as an empty list
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pluralName/>
Is there a way to do this without just manually inserting the xml strings?
Update
With some help from Michael Glavasevich I was able to do this with one caveat, the individual elements <Item>s
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> String jaxb(Collection<T> elements, Class<T> elementClass, String plural){
try {
T[] array = (T[]) Array.newInstance(elementClass, elements.size());
elements.toArray(array);
JAXBContext jc = JAXBContext.newInstance(array.getClass());
JAXBElement<T[]> topElement = new JAXBElement(new QName(plural), array.getClass(), array);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(topElement, writer);
return writer.toString();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
Then the result becomes
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Basketballs>
<item>basketball one</item>
<item>basketball two</item>
</Basketballs>
source
share