Printing a JAXB generated bean
I have a JAXB data class which is generated from wsimport
and I'd like to print it to the console and/or log. Unfortunately a toString is not generated.
What's the easiest way to p开发者_高级运维rint the data object? It doesn't matter whether the output is the original XML or something else, as long as it's readable.
It looks like the class is a valid bean (properly named getters and setters) so anything that works with beans is probably fine too.
For printing to the console, try this:
jaxbContext.createMarshaller().marshal(jaxbObject, System.out);
To get it into a String
, use a StringWriter
:
StringWriter writer = new StringWriter();
jaxbContext.createMarshaller().marshal(jaxbObject, writer);
String xmlString = writer.toString();
To get the JAXBContext object you need to do the following:
JAXBContext jaxbContext = JAXBContext.newInstance(<WhateverClass>.class);
Where <WhateverClass>
is the class literal for the type that jaxbObject
is. You should also be able to do:
JAXBContext jaxbContext = JAXBContext.newInstance(jaxbObject.getClass());
Depending on where you are defining the context and your stylistic preference. JAXBContext
is thread-safe so it is good to define one instance and share it. Marshaller
and Unmarshaller
make no such guarantees though. So they need to be created on demand.
精彩评论