javax.xml.bind.JAXB.unmarshal() Method



Description

The Javax.xml.bind.JAXB.unmarshal(Source xml, Class<T> type) method reads in a Java object tree from the given XML input.

Declaration

Following is the declaration for javax.xml.bind.JAXB.unmarshal(Reader xml, Class<T> type) method

public static <T> T unmarshal(Reader xml, Class<T> type)

Parameters

  • xml − The character stream is read as an XML infoset. The encoding declaration in the XML will be ignored. Upon a successful completion, the stream will be closed by this method.

  • type − A class type to be unmarshaled.

Return Value

The method retutns object of type Class<T>

Exception

NA

Example

The following example shows the usage of javax.xml.bind.JAXB.unmarshal(Reader xml, Class<T> type) method. To proceed, consider the following Student class which will be used to have objects for unmarshalling purpose −

package com.tutorialspoint;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement
public class Student{
 
   String name;
   int age;
   int id;

   public String getName(){
      return name;
   }

   @XmlElement
   public void setName(String name){
      this.name = name;
   }

   public int getAge(){
      return age;
   }

   @XmlElement
   public void setAge(int age){
      this.age = age;
   }

   public int getId(){
      return id;
   }

   @XmlAttribute
   public void setId(int id){
      this.id = id;
   }
}

Now let us create main class which will be used to marshal ie. convert Student object into an XML file. This example unmarshals the Student.xml file to object and prints.

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.bind.JAXB;
import javax.xml.transform.stream.StreamSource;

public class JAXBDemo {

   public static void main(String[] args) throws IOException {

      try {

         // create new source
         FileInputStream fis = new FileInputStream("Student.xml");
         StreamSource src = new StreamSource();
         src.setInputStream(fis);


         // marshal object to file input stream
         Student st = JAXB.unmarshal(src, Student.class);

         // prints
         System.out.println("Age : " + st.getAge());
         System.out.println("Name : " + st.getName());

      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

To create document, an XML file is needed as input. The XML file is named as Student.xml

<?xml version = "1.0" encoding = "UTF-8" standalone = "no"?>
<student id = "10">
   <age>14</age>
   <name>Soniya</name>
</student>

Before we proceed for compilation, we need to make sure that that we download JAXB2.xxx.jar and put it in our CLASSPATH. Once setup is ready, let us compile and run the above program, this will produce the following result −

Age : 14
Name : Soniya
javax_xml_bind_jaxb.htm
Advertisements