我使用以下代码使用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声明?
答案 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)