Java Reference
In-Depth Information
Patients patients = new Patients();
List<Patient> patientList = patients.getPatient();
Patient p = new Patient();
p.setId(BigInteger.valueOf(1));
p.setName("John Doe");
p.setDiagnosis("Schizophrenia");
patientList.add(p);
JAXBContext jc = JAXBContext.newInstance(context);
Marshaller m = jc.createMarshaller();
m.marshal(patients, new FileOutputStream(xmlFile));
}
The previous code produces an unformatted but well-formed and valid XML docu-
ment. For readability, the XML document is formatted here:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<patients>
<patient id="1">
<name>John Doe</name>
<diagnosis>Schizophrenia</diagnosis>
</patient>
</patients>
Note The getPatient() method in the previous code returns a list of patient ob-
jects instead of a single patient. This is a naming oddity of the JAXB code generation
from the XSD schema in this example.
How It Works
A Marshaller object understands JAXB annotations. As it processes classes, it uses
the JAXB annotations to provide the context needed to create the object tree in XML.
You can run the previous code from the
org.java8recipes.chapter20.recipe20_7.MarshalPatients applic-
ation using the following command line:
Search WWH ::




Custom Search