I want to marshal many objects into a single xml file. This is going well, except that my marshaller insists on adding an extra <?xml version="1.0" ?> before each object.
- What’s the preferred way to marshal many objects into the same file?
- If nothing else, what’s the best way to get rid of these extraneous xml declarations?
My current code:
JAXBContext jc = JAXBContext.newInstance(relevantClasses);
Marshaller m = jc.createMarshaller();
XMLOutputFactory xof = XMLOutputFactory.newFactory();
XMLStreamWriter xsw = xof.createXMLStreamWriter(Channels.newOutputStream(fileWriteChannel), "UTF-8");
xsw.writeStartDocument("UTF-8", "1");
m.marshal(object1, xsw);
m.marshal(object2, xsw);
xsw.close();
This works great, and I get the <object1> and <object2> data I expect… it just has an additional <?xml version="1.0" ?> before each object.
An XML document always has one root element, so marshalling several objects to a single file won’t lead to valid XML.
You should have one root object with an Object1 element, and an Object2 element, and marshal this root object.
Otherwise, the Marshaller API doc says: