JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(DeleteXML.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
jaxbMarshaller.marshal(deleteXML, outputStream);
parentXML = outputStream.toString("utf-8");
} catch (Exception e) {
e.printStackTrace();
try {
jaxbContext = JAXBContext.newInstance(DeleteXML.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
jaxbMarshaller.marshal(deleteXML, outputStream);
parentXML = outputStream.toString("utf-8");
} catch (Exception e) {
e.printStackTrace();
}
用这种方法生成xml文件的时候,一定要在toString()里面在加一个编码,要不然会出现乱码的。
附加一个编码问题的博客:http://blog.youkuaiyun.com/isle_t/article/details/2413309