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



Description

The Javax.xml.bind.JAXB.unmarshal(URI 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(URI xml, Class<T> type) method

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

Parameters

  • xml − The URI is turned into URL and then follows the handling of URL.

  • type − A class type to be unmarshaled.

Return Value

This method does not return any value.

Exception

NA

Example

The following example shows the usage of javax.xml.bind.JAXB.unmarshal(URI xml, Class<T> type) method. To proceed, consider the following Student class which will be used to have objects for marshalling 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 unmarshal ie. convert Student.xml to JAXB object.

package com.tutorialspoint;

import java.io.IOException;
import java.net.URI;

import javax.xml.bind.JAXB;

public class JAXBDemo {
   public static void main(String[] args) throws IOException {
      
      try {
         // create new URI       
         String xmlString = "file:///C:/Student.xml";
         URI uri = new URI(xmlString);

         // unmarshal xml to JAXB object
         Student st = JAXB.unmarshal(uri, Student.class);
         
         // prints
         System.out.println("Age : "+st.getAge());
         System.out.println("Name : "+st.getName());
         
      }catch(Exception ex) {
         ex.printStackTrace();
      }
   }
}

Below input XML string, Student.xml −

<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?>
<student id = "10">
   <age>12</age>
   <name>Malik</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 : 12
Name : Malik
javax_xml_bind_jaxb.htm
Advertisements