Monday, 4 April 2016

What is UnMarshalling and how to unmarshal ?


UnMarshalling

Generates content tree from XML document instance through JAXB binding framework.
Sources for unMarshalling can be: Files/documents, inputStream, String buffers, DOM nodes, SAX Sources.

javax.xml.bind.JAXBContext
  • Provides entry point to the JAXB API and created via newInstance(contextPath)
    contextPath contains a list of Java package names that contain schema derived interfaces and classes :

    JAXBContext 
    jc = JAXBContext.newInstance("com.genius.foo:com.genius.bar");
  • Unmarshaller, Marshaller, Validator object are created from JAXBContext object

javax.xml.bind.Unmarshaller
Java Interface that governs the process of deserializing XML data (XML document instance) into newly created Java content tree.
Optionally, validates XML data as it is unmarshalled.


Unmarshalling Examples

Unmarshalling from a File
// Create JAXBContext object
JAXBContext jc = JAXBContext.newInstance( "com.genius.foo" );
// Create Unmarshaller object
Unmarshaller u = jc.createUnmarshaller();
// Unmarshall a XML document which is in the form of File
Object o = u.unmarshal( new File( "example.xml" ) );

Unmarshalling from an InputStream
InputStream is = new FileInputStream( "example.xml" );
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
Object o = u.unmarshal( is );

Unmarshalling from a URL
JAXBContext jc = JAXBContext.newInstance("com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
URL url = new URL( "http: //genius.prog/example.xml" );
Object o = u.unmarshal( url );

Unmarshalling from a StringBuffer
JAXBContext jc = JAXBContext.newInstance( "com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
StringBuffer xmlStr = new StringBuffer( "..." );
Object o = u.unmarshal( new StreamSource( new StringReader(xmlStr.toString() ) ) );

Turn off validation during Unmarshalling
JAXBContext jc = JAXBContext.newInstance( "com.genius.foo" );
Unmarshaller u = jc.createUnmarshaller();
u.setValidating(false);
Object o = u.unmarshal( new File( "example.xml" ) );

No comments:

Post a Comment

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