設置Marshaller.JAXB_FORMATTED_OUTPUT
可能不利於記錄。
反而抑制XML Prolog (or Declaration)
與Marshaller.JAXB_FRAGMENT
。
public static <J> String printXml(final J instance) throws JAXBException {
return printXml(instance, instance.getClass());
}
public static <J> String printXml(final J instance,
final Class<?>... classesToBeBound)
throws JAXBException {
final JAXBContext context = JAXBContext.newInstance(classesToBeBound);
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.marshal(instance, output);
// output.flush(); // Nasty IOException
final String jaxbEncoding = (String) marshaller.getProperty(
Marshaller.JAXB_ENCODING);
try {
return new String(output.toByteArray(), jaxbEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException(uee);
}
}
會打印出這樣的單行。
<user><name>cristi</name><surname>kevin</surname></user>
這已無關,與JAX-WS,您只需要JAXB(標籤是正確的,但你提到的JAX-WS文本)。 – 2010-03-17 12:01:00