Monday, 4 April 2016

What is Marshalling and how to marshal ?


Content tree may be marshalled by passing it to marshal method of Marshaller object.

javax.xml.bind.Marshaller
An interface that governs the process of serializing Java content trees back into XML data.


Marshalling examples

Marshalling to a File
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject) u.unmarshal( new File( "foo.xml") );
Marshaller m = jc.createMarshaller();
OutputStream os = new FileOutputStream( "genius.xml" );
m.marshal( obj, os );

Marshalling to a OutputStream
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject) u.unmarshal( new File( "foo.xml") );
Marshaller m = jc.createMarshaller();
m.marshal( obj, System.out );

Marshalling to a Writer
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject) u.unmarshal( new File( "foo.xml") );
Marshaller m = jc.createMarshaller();
m.marshal( obj, new PrintWriter( System.out ) );

Marshalling to a javax.xml.transform.StreamResult
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
FooObject obj = (FooObject)u.unmarshal( new File( "foo.xml") );
Marshaller m = jc.createMarshaller();
StreamResult result = new StreamResult( System.out );
m.marshal( obj, result );

No comments:

Post a Comment

Note: only a member of this blog may post a comment.