0

我正在使用以下代码使用 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 声明?

4

2 回答 2

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。

于 2013-04-13T22:27:01.107 回答
1

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

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

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
于 2013-04-14T13:53:15.827 回答