Java: jaxb, esempio di marshall e unmarshall utilizzando i generics

Utilizzando Jaxb, per non riscrivere le stesse quattro righe di codice ogni volta che devo eseguire il marshall o unmarshall di diverse classi su diversi schemi o file xml, ho utilizzato i generics. I metodi unMarshall e marshall sotto descritti non hanno peli sullo stomaco, e accettano tutto quello che gli viene proposto.

La classe di esempio JaxbController

 
public class JaxbController {
 
[...]
 
	public <T> T unMarshall(Class<T> classe, InputStream in, InputStream xsd)
			throws JAXBException, SAXException {
 
		JAXBContext jc = JAXBContext.newInstance(classe);
		Unmarshaller unmarshaller = jc.createUnmarshaller();
 
		Source schemaSource = new StreamSource(xsd);
		SchemaFactory sf = SchemaFactory
				.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
 
		Schema schema = sf.newSchema(schemaSource);
 
		unmarshaller.setSchema(schema);
 
		@SuppressWarnings("unchecked")
		T result = (T) unmarshaller.unmarshal(in);
 
		return (T) result;
	}
 
	public <T> void marshall(T root, Writer writer) throws JAXBException {
 
		JAXBContext jc = JAXBContext.newInstance(root.getClass());
 
		Marshaller marshaller = jc.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 
		marshaller.marshal(root, writer);
 
	}	
 
[...]

Dove i parametri in ingresso sono:

  • Class classe: La classe che mappa l’elemento radice del nostro XML
  • InputStream in: l’XML sotto forma di InputStream
  • InputStream xsd: l’XSD sotto forma di Inputstream
  • T root: L’istanza della classe che mappa la radice del documento XML
  • Writer writer: Stream che contiene la stringa XML

Esempio di utilizzo

Supponiamo di avere:

  • Un insieme di classi che mappano l’XML di cui LaMiaRadiceXML mappa l’elemento radice
  • Uno schema XSD test.xsd (da cui abbiamo creato le classi)
  • Un file XMl test.xml

unMarshall (con validazione dell’XML sull’XSD)

ObjectFactory factory = new ObjectFactory();
LaMiaRadiceXML root = factory.createLaMiaRadiceXML();
 
InputStream in = getClass().getResourceAsStream("/test.xml");
InputStream xsd = getClass().getResourceAsStream("/test.xsd");
 
JaxbController jb = new JaxbController();
 
try {
 
	root = jb.unMarshall(LaMiaRootXML.class, in, xsd);
 
} catch (JAXBException e) {
	e.printStackTrace();
} catch (SAXException e) {
	e.printStackTrace();
}

Marshall (verso una stringa)

 
	ObjectFactory factory = new ObjectFactory();
	LaMiaRadiceXML root = factory.createLaMiaRadiceXML();		
 
	root.setTitolo("La montagna incantata");	
 
	JaxbController jb = new JaxbController();
 
	StringWriter sw = new StringWriter();
 
	try {
		jb.marshall(LaMiaRadiceXML, sw);
	} catch (JAXBException e) {
		e.printStackTrace();
	}
 
	System.out.println(sw.toString());

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>