I agree with using JAXB.
Starting from XML Schema (Generate classes from XML Schema)
You can use JAXB to generate Java source code from XML Schema. Below are the instructions for doing this with EclipseLink JAXB (MOXy):
Java SE 6 comes with the Metro JAXB XJC compiler it can be found in the bin directory of your JDK installation:
C:\Program Files\Java\jdk1.6.0_20\bin>xjc -d outputDir mySchema.xsd
The Dali plug-in in Eclipse also has this support see section on JAXB class generation:
Starting from Objects
With your object model you may find the XPath based mapping extension in MOXy JAXB useful:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
@XmlPath("name/firstname/text()")
private String firstName;
@XmlPath("name/lastname/text()")
private String lastName;
// ...
}
Can be used with the following demo code to work with your XML:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Person person = (Person) unmarshaller.unmarshal(new File("input.xml"));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(person, System.out);
}
}
For more information on XPath based mappings see:
For the "born" element you might find JAXB's XmlAdapter helpful: