Riley Lark
Riley Lark

Reputation: 20890

JAXB marshalling many objects to one file

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.

  1. What's the preferred way to marshal many objects into the same file?
  2. 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.

Upvotes: 4

Views: 4625

Answers (2)

rbaha
rbaha

Reputation: 140

I think you should add the root like

@XmlRootElement(name = "Name")
public class EntityName   {

}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691755

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:

Supported Properties

[...]

jaxb.fragment - value must be a java.lang.Boolean This property determines whether or not document level events will be generated by the Marshaller. If the property is not specified, the default is false. This property has different implications depending on which marshal api you are using - when this property is set to true:

[...]

marshal(Object,XMLStreamWriter) - the Marshaller will not generate XMLStreamConstants.START_DOCUMENT and XMLStreamConstants.END_DOCUMENT events.

Upvotes: 6

Related Questions