javax.xml.bind.JAXBContext.newInstance() Method



Description

The javax.xml.bind.JAXBContext.newInstance(String contextPath) method obtains a new instance of a JAXBContext class.

This is a convenience method to invoke the newInstance(String,ClassLoader) method with the context class loader of the current thread.

Declaration

Following is the declaration for javax.xml.bind.JAXBContext.newInstance(String contextPath) method

public static JAXBContext newInstance(String contextPath)

Parameters

contextPath − contextPath as String.

Return Value

The method returns a new instance of a JAXBContext class.

Exception

JAXBException − if an error was encountered while creating the JAXBContext.

Example

The following example shows the usage of javax.xml.bind.JAXBContext.newInstance(String contextPath) method. To proceed, consider the following Catalog ckass which will be used for unmarshalling purpose −

package com.tutorialspoint.gen;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
   "cd"
})
@XmlRootElement(name = "catalog")
public class Catalog {
   
   @XmlElement(required = true)
   protected List<Catalog.Cd> cd;
   
   public List<Catalog.Cd> getCd() {
      if (cd == null) {
         cd = new ArrayList<Catalog.Cd>();
      }
      return this.cd;
   }
   
   @XmlAccessorType(XmlAccessType.FIELD)
   @XmlType(name = "", propOrder = {
      "title",
      "artist",
      "country",
      "company",
      "price",
      "year"
   })
   
   public static class Cd {
      
      @XmlElement(required = true)
      protected String title;
      @XmlElement(required = true)
      protected String artist;
      @XmlElement(required = true)
      protected String country;
      @XmlElement(required = true)
      protected String company;
      @XmlElement(required = true)
      protected BigDecimal price;
      @XmlSchemaType(name = "unsignedShort")
      protected int year;

      public String getTitle() {
         return title;
      }
      
      public void setTitle(String value) {
         this.title = value;
      }
      
      public String getArtist() {
         return artist;
      }
      
      public void setArtist(String value) {
         this.artist = value;
      }

      public String getCountry() {
         return country;
      }

      public void setCountry(String value) {
         this.country = value;
      }

      public String getCompany() {
         return company;
      }
      
      public void setCompany(String value) {
         this.company = value;
      }
      
      public BigDecimal getPrice() {
         return price;
      }
      
      public void setPrice(BigDecimal value) {
         this.price = value;
      }
      
      public int getYear() {
         return year;
      }
      
      public void setYear(int value) {
         this.year = value;
      }
   }
}

An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. The Java representation of XML content can consist of schema derived interfaces and classes representing the binding of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in this class.

package com.tutorialspoint.gen;

import javax.xml.bind.annotation.XmlRegistry;

@XmlRegistry
public class ObjectFactory {
   
   public ObjectFactory() {
   }
   
   public Catalog createCatalog() {
      return new Catalog();
   }
   
   public Catalog.Cd createCatalogCd() {
      return new Catalog.Cd();
   }
}

Now let us create main class which will be used to unmarshal ie. convert Catalog.xml into an Catalog object. This example unmarshals the Catalog.xml to JAXB object and prints the values at STDOUT.

package com.tutorialspoint;

import java.io.FileInputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import com.tutorialspoint.gen.*;
import com.tutorialspoint.gen.Catalog.Cd;


public class JAXBContextDemo {
   public static void main(String[] args) {

      try {
         // create JAXBContext which will be used to create a Binder
         JAXBContext jc = JAXBContext.newInstance("com.tutorialspoint.gen");
        
         // create new file input stream
         FileInputStream fis = new FileInputStream("Catalog.xml");
         
         // unmarshaller obj to convert xml data to java content tree
         Unmarshaller u = jc.createUnmarshaller();
         
         // unmarshaller xml data to java content tree
         Catalog c = (Catalog)u.unmarshal(fis);
         
         for (Cd cd : c.getCd()) {
            System.out.println("Artist: "+cd.getArtist());
            System.out.println("Company: "+cd.getCompany());
            System.out.println("Country: "+cd.getCountry());
            System.out.println("Title: "+cd.getTitle());
            System.out.println("Year: "+cd.getYear());
            System.out.println("----------------------");
         }
      }catch(Exception ex) {
         ex.printStackTrace();
      }
   }
}

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 −

Artist: Bob Dylan
Company: Columbia
Country: USA
Title: Empire Burlesque
Year: 1985
----------------------
Artist: Bonnie Tyler
Company: CBS Records
Country: UK
Title: Hide your heart
Year: 1988
----------------------
Artist: Dolly Parton
Company: RCA
Country: USA
Title: Greatest Hits
Year: 1982
----------------------
Artist: Gary Moore
Company: Virgin records
Country: UK
Title: Still got the blues
Year: 1990
----------------------
Artist: Eros Ramazzotti
Company: BMG
Country: EU
Title: Eros
Year: 1997
----------------------
Artist: Bee Gees
Company: Polydor
Country: UK
Title: One night only
Year: 1998
----------------------
Artist: Dr.Hook
Company: CBS
Country: UK
Title: Sylvias Mother
Year: 1973
----------------------
Artist: Rod Stewart
Company: Pickwick
Country: UK
Title: Maggie May
Year: 1990
----------------------
Artist: Andrea Bocelli
Company: Polydor
Country: EU
Title: Romanza
Year: 1996
----------------------
Artist: Percy Sledge
Company: Atlantic
Country: USA
Title: When a man loves a woman
Year: 1987
----------------------
Artist: Savage Rose
Company: Mega
Country: EU
Title: Black angel
Year: 1995
----------------------
Artist: Many
Company: Grammy
Country: USA
Title: 1999 Grammy Nominees
Year: 1999
----------------------
Artist: Kenny Rogers
Company: Mucik Master
Country: UK
Title: For the good times
Year: 1995
----------------------
Artist: Will Smith
Company: Columbia
Country: USA
Title: Big Willie style
Year: 1997
----------------------
Artist: Van Morrison
Company: Polydor
Country: UK
Title: Tupelo Honey
Year: 1971
----------------------
Artist: Jorn Hoel
Company: WEA
Country: Norway
Title: Soulsville
Year: 1996
----------------------
Artist: Cat Stevens
Company: Island
Country: UK
Title: The very best of
Year: 1990
----------------------
Artist: Sam Brown
Company: A and M
Country: UK
Title: Stop
Year: 1988
----------------------
Artist: T`Pau
Company: Siren
Country: UK
Title: Bridge of Spies
Year: 1987
----------------------
Artist: Tina Turner
Company: Capitol
Country: UK
Title: Private Dancer
Year: 1983
----------------------
Artist: Kim Larsen
Company: Medley
Country: EU
Title: Midt om natten
Year: 1983
----------------------
Artist: Luciano Pavarotti
Company: DECCA
Country: UK
Title: Pavarotti Gala Concert
Year: 1991
----------------------
Artist: Otis Redding
Company: Atlantic
Country: USA
Title: The dock of the bay
Year: 1987
----------------------
Artist: Simply Red
Company: Elektra
Country: EU
Title: Picture book
Year: 1985
----------------------
Artist: The Communards
Company: London
Country: UK
Title: Red
Year: 1987
----------------------
Artist: Joe Cocker
Company: EMI
Country: USA
Title: Unchain my heart
Year: 1987
----------------------
javax_xml_bind_jaxbcontext.htm
Advertisements