XML > JAXB > Generate schema from java classes
Generate schema from java classes
The following example shows generating an XML schema document from a POJOs.
We can customize the schema generation by providing an implementation of
SchemaOutputResolver .
package com.bethecoder.tutorials.jaxb.common;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Student {
private String firstName;
private String lastName;
private int age;
private String hobby;
private Date dob;
/**
* NOTE : Should have a no-arg default constructor.
*/
public Student () {
}
public Student ( String firstName, String lastName, int age, String hobby,
Date dob ) {
super () ;
this .firstName = firstName;
this .lastName = lastName;
this .age = age;
this .hobby = hobby;
this .dob = dob;
}
public String getFirstName () {
return firstName;
}
public void setFirstName ( String firstName ) {
this .firstName = firstName;
}
public String getLastName () {
return lastName;
}
public void setLastName ( String lastName ) {
this .lastName = lastName;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public Date getDob () {
return dob;
}
public void setDob ( Date dob ) {
this .dob = dob;
}
}
package com.bethecoder.tutorials.jaxb.tests;
import java.io.File;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import com.bethecoder.tutorials.jaxb.common.BinaryData;
public class SchemaGeneration {
public static void main ( String [] args ) throws JAXBException, IOException {
JAXBContext context = JAXBContext.newInstance ( BinaryData. class ) ;
context.generateSchema ( new ClassToSchemaOutputResolver ()) ;
}
}
class ClassToSchemaOutputResolver extends SchemaOutputResolver {
public Result createOutput ( String namespaceUri, String suggestedFileName ) throws IOException {
System.out.println ( "Suggested File Name : " + suggestedFileName ) ;
return new StreamResult ( new File ( suggestedFileName )) ;
}
}
It gives the following output,