/**
  * Cenverte o objeto informado para uma String que representa o XML do objeto.
  *
  * @param <T> Tipo generico que informa a classe
  * @param object O objeto a ser convertido. A classe deste objeto deve conter as anotações de
  *     JAXB.
  * @param schemaLocation {@link URL} do schema.
  * @return
  * @throws JAXBException
  */
 @SuppressWarnings("unchecked")
 public static <T> String marshal(T object, URL schemaLocation) throws JAXBException {
   Class<T> objClass = (Class<T>) object.getClass();
   JAXBContext context = JAXBContext.newInstance(objClass);
   Marshaller marshaller = context.createMarshaller();
   StringWriter sWriter = new StringWriter();
   XmlSchema xmlSchema = objClass.getPackage().getAnnotation(XmlSchema.class);
   if (xmlSchema != null && xmlSchema.namespace() != null) {
     XmlType xmlType = objClass.getAnnotation(XmlType.class);
     if (xmlType != null && xmlType.name() != null) {
       QName qName = new QName(xmlSchema.namespace(), xmlType.name());
       JAXBElement<T> elem = new JAXBElement<T>(qName, objClass, object);
       if (schemaLocation != null) {
         SchemaFactory schemaFactory =
             SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
         try {
           Schema schema = schemaFactory.newSchema(schemaLocation);
           marshaller.setSchema(schema);
         } catch (SAXException e) {
           e.printStackTrace();
         }
       }
       marshaller.marshal(elem, sWriter);
       return sWriter.toString();
     } else {
       throw new JAXBException("The xmlType could not be identified in class annotation");
     }
   } else {
     throw new JAXBException("The namespace could not be identified from package-info class");
   }
 }
Exemple #2
0
 private static String getNamespace(Class<?> jaxbClass, Map<Package, String> pkgToNamespace) {
   Package pkg = jaxbClass.getPackage();
   String namespace = pkgToNamespace.get(pkg);
   if (namespace == null) {
     XmlSchema schemaAnnot = pkg.getAnnotation(XmlSchema.class);
     if (schemaAnnot != null) {
       namespace = schemaAnnot.namespace();
       // XmlNs[] xmlns = schemaAnnot.xmlns();  Useful if we need prefix for namespace
       pkgToNamespace.put(pkg, namespace);
     }
   }
   return namespace;
 }