JAXB - 未创建XML声明

时间:2013-04-13 21:44:17

标签: java xml jaxb

我使用以下代码使用JAXB创建XML,但是在创建XML时,不包括XML声明。

代码:

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声明:

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

如何让它输出XML声明?

2 个答案:

答案 0 :(得分:1)

您不需要写入文件,您可以在内存中执行此操作:

...
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();
顺便说一句,你应该考虑使用UTF-8。

答案 1 :(得分:0)

这个问题得到了很好的回答here

总而言之,您需要做的就是:

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