I have a class, let's call it User annotated with @XmlRootElement
, with some properties (name, surname etc).
I use this class for REST operations, as application/xml
.
The client will POST User class so i want to keep the values in the log.
Is there any method in jaxb to prints out this object as xml?
For instance:
log.info("Customers sent: "+user.whichMeth开发者_如何学JAVAod());
should produce this output:
Customer sent:
<user> <name>cristi</name> <surname>kevin</surname> </user>
Thanks.
You can make this as a common method accessible by your endpoints.
public String toXml(JAXBElement element) {
try {
JAXBContext jc = JAXBContext.newInstance(element.getValue().getClass());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(element, baos);
return baos.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
Found:)
public void toXml() {
try {
JAXBContext ctx = JAXBContext.newInstance(User.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(this, System.out);
}
catch (Exception
e) {
//catch exception
}
}
Call it like:
log.info("Customers sent: "+user.toXml());
Setting Marshaller.JAXB_FORMATTED_OUTPUT
may be not good for logging.
Instead suppress XML Prolog (or Declaration)
with 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);
}
}
will prints a single line like this.
<user><name>cristi</name><surname>kevin</surname></user>
public String toXml(Event event) {
ByteArrayOutputStream baos = null;
try {
JAXBContext jc = JAXBContext.newInstance(event.getClass());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
baos = new ByteArrayOutputStream();
marshaller.marshal(event, baos);
return baos.toString();
} catch (JAXBException e) {
LOGGER.log(Level.SEVERE, " problem in Logging raw XML :"+e.getMessage());
}
return baos.toString();
This Works well
精彩评论