Unmarshalling

Unmarshalling is the process of reading contents of an XML document and creating Java objects that represent the content and organization of the XML document. Unmarshalling uses the XJC-generated Java classes to read the XML document.

The binding APIs in the JAXB architecture provide the Unmarshaller class that has a method called unmarshal. This method reads the input XML document and returns a Java object containing the copy of the data contents from the XML document. The code snippet on the right displays the customers.xml document and the steps to unmarshal the XML document. To unmarshal a document you need to:

  • Create a JAXBContext object.
    The following code creates a JAXBContext object:

  JAXBContext jc = JAXBContext.newInstance("customer");

This object is created to access the interfaces in JAXB. After creating the JAXBContext object, you need to specify a context path. The context path is a package name that contains interfaces generated by the XJC. In the preceding code snippet, customer is the context path.

  • Create an Unmarshaller object.
    The following statement creates an Unmarshaller object that controls the process of unmarshalling:

  Unmarshaller u = jc.createUnmarshaller();

  • Call the unmarshal method and specify methods that process the Java objects.
    The unmarshal method unmarshals the XML document. In the following declarations, the unmarshal method reads the input customers.xml XML document and returns the cust Java object containing the copy of the data contents from the XML document:

  Customer cust = (Customer)u.unmarshal(
  new FileInputStream("customers.xml"));


Applications can use the Java object to generate the required information. The following declaration displays James Gosling in the console:

  System.out.println (cust.getFirstName());
  System.out.println (cust.getLastName());

The get methods, cust.getFirstName() and cust.getLastName(), are defined in the CustomerType.java class created by the XJC.

Steps to Unmarshal an XML Document
----------------------------------------------

// Create a JAXBContext object
JAXBContext jc = JAXBContext.newInstance( "customer" );

// Create an Unmarshaller object
Unmarshaller u = jc.createUnmarshaller();

// Unmarshalling a customer instance document
Customer cust = Customer)u.unmarshal( new FileInputStream( "customers.xml" )
);
cust.getFirstName();
System.out.println (cust.getFirstName());
System.out.println (cust.getLastName());

customers.xml Document
----------------------------------------------

<?xml version="1.0"?>
  <Customer>
    <FirstName>James</FirstName>
    <LastName>Gosling</LastName>
  </Customer>

Click the Next button to continue.