Print JAXB Annotated Object


/ Published in: Java
Save to your folder(s)

Method to print on System Out a JAXB annotated object


Copy this code and paste it in your HTML
  1. private static void printJaxbObject(
  2. Object jaxbObject) {
  3. JAXBContext jaxbContext;
  4. try {
  5. jaxbContext = JAXBContext.newInstance(jaxbObject.getClass());
  6. Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
  7.  
  8. String namespace = "";
  9. if(jaxbObject.getClass().getPackage().isAnnotationPresent(javax.xml.bind.annotation.XmlSchema.class)) {
  10. javax.xml.bind.annotation.XmlSchema schema = jaxbObject.getClass().getPackage().getAnnotation(javax.xml.bind.annotation.XmlSchema.class);
  11. namespace = schema.namespace();
  12. }
  13.  
  14. // output pretty printed
  15. jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  16.  
  17. JAXBElement<?> r = new JAXBElement(new QName(namespace, jaxbObject.getClass().getSimpleName()), jaxbObject.getClass(), jaxbObject);
  18. jaxbMarshaller.marshal(r, System.out);
  19. } catch (JAXBException e) {
  20. // TODO Auto-generated catch block
  21. e.printStackTrace();
  22. }
  23. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.