Colin747
Colin747

Reputation: 5013

JAXB - XML declaration not being created

I am using the following code to create XML using JAXB, however when the XML is created the XML declaration is not included.

Code:

ServletContext ctx = getServletContext();
            String filePath = ctx.getRealPath("/xml/"+username + ".xml");

            File file = new File(filePath);
            JAXBContext context= JAXBContext.newInstance("com.q1labs.qa.xmlgenerator.model.generatedxmlclasses");
            Marshaller jaxbMarshaller = context.createMarshaller();

            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            OutputStream os = new FileOutputStream(file);
            jaxbMarshaller.marshal(test, os);

            response.setContentType("text/plain");
            response.setHeader("Content-Disposition",
                             "attachment;filename=xmlTest.xml");

            InputStream is = ctx.getResourceAsStream("/xml/"+username + ".xml");

XML Declaration:

<?xml version="1.0" encoding="ISO-8859-1"?>

How can I get it to output the XML declaration?

Upvotes: 0

Views: 6574

Answers (2)

marc2112
marc2112

Reputation: 153

This question has been answered pretty well here

To sum up, all you should need to do is this:

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);

Upvotes: 1

Cebence
Cebence

Reputation: 2416

You don't need to write to a file, you can do it in-memory like this:

...
ByteArrayOutputStream os = new ByteArrayOutputStream();
jaxbMarshaller.marshal(test, os);

StringBuffer content = new StringBuffer("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
content.append(os.toString());
System.out.println("jaxb xml = " + os.toString());

response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=xmlTest.xml");

String generatedXML = content.toString();
System.out.println("full xml = " + generatedXML);
InputStream is = new ByteArrayInputStream(generatedXML);

final int bufferSize = 4096;
OutputStream output = new BufferedOutputStream(response.getOutputStream(), bufferSize);
for (int length = 0; (length = is.read(buffer)) > 0;) {
  output.write(buffer, 0, length);
}
output.flush();
output.close();

BTW, you should consider using UTF-8.

Upvotes: 1

Related Questions