How to use Castor's XMLContext for un-/marshalling Intended Audience Prerequisites Domain classes Basic code fragments
Intended Audience
Anyone who wants to use Castor XML for XML data binding, namely marshalling and
unmarshalling operations.
Prerequisites
You should have downloaded the Castor binaries or included Castor as a dependency in a
Maven project.
Domain classes
For the purpose of showcasing the use of the XMLContext class, let's assume we
have a simple Person class as follows:
import java.util.Date;
/** An simple person class */
public class Person implements java.io.Serializable {
/** The name of the person */
private String name = null;
/** The Date of birth */
private Date dob = null;
/** Creates a Person with no name */
public Person() {
super();
}
/** Creates a Person with the given name */
public Person(String name) {
this.name = name;
}
/**
* @return date of birth of the person
*/
public Date getDateOfBirth() {
return dob;
}
/**
* @return name of the person
*/
public String getName() {
return name;
}
/**
* Sets the date of birth of the person
* @param name the name of the person
*/
public void setDateOfBirth(Date dob) {
this.dob = dob;
}
/**
* Sets the name of the person
* @param name the name of the person
*/
public void setName(String name) {
this.name = name;
}
} |
|
Basic code fragments
Starting with Castor 1.1.2, the XMLContext
class provides a bootstrap mechanism for Castor XML, and allows easy (and efficient)
instantiation of Marshaller and
Unmarshaller
instances, which can be used to perform basic XML data binding operations.
Below is a code sample that shows how to use the XMLContext class for
umarshalling a Person instance using an
Unmarshaller. In this example,
a mapping file is used.
import org.exolab.castor.xml.XMLContext;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.xml.Unmarshaller;
//create a Mapping instance
Mapping mapping = XMLContext.createMapping();
mapping.loadMapping("mapping.xml");
// create an XMLContext instance and set mapping
XMLContext context = new XMLContext();
context.addMapping(mapping);
// create a new Unmarshaller
Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setClass(Person.class);
// Create a Reader to the file to unmarshal from
Reader reader = new FileReader("test.xml");
// Unmarshal the person object
Person person = (Person) unmarshaller.unmarshal(reader); |
|
As shown above, the XMLContext
class offers various factory methods to obtain a new
Marshaller,
Unmarshaller or
Mapping instance.
When you need more than one Unmarshaller
instance in your application, please call
createUnmarshaller as required. As all
Unmarshaller instances are created from the very same XMLContext
instance, overhead will be minimal. Please note, though, that an
Unmarshaller instance is not thread-safe.
|