I have structure like
class Header{
List<Item> items
}
Both Header and Item have xsd schema. I need to write Header with items inside it into xml file without populating List in memory since there could be up to 10000 elements. I can't do something like marshaller.marshal(header) since items are not populated. I see the following solution: map each item using marshaller into xml string and write it into file item by item. Before create manually header from pojo and close it also manually.
Header doc=header data withoutitems
int counter=0;
//call it 10000 times
void writeItem(Item item){
if(counter==0){
FileWriter writer=new FileWriter(path);
String header1 = convertToXmlString(doc.getHeader1());
String header2 = convertToXmlString(doc.getHeader2());
writer.write("<?xml bla>")
writer.write("<myroot>")
writer.write(header1)
writer.write(header2)
}
writer.write(jaxbMarshaler.marshal(item));
counter++
if(counter==10000){
writer.write("</myroot>")
}
}
Is there more elegant solution? I can't (don't want) use plain Stax since Item structure is pretty huge and difficult and iterating every element is something overkill. Also in my solution how to synchronize namespaces so header and all items have the same prefixes?
Refer to JAXB Fragmented Marshalling
You basically combine XMLStreamWriter
with JAXB fragments.