Java Reference
In-Depth Information
public void run(String xmlFile, String context)
throws JAXBException, FileNotFoundException {
JAXBContext jc = JAXBContext.newInstance(context);
Unmarshaller u = jc.createUnmarshaller();
FileInputStream fis = new FileInputStream(xmlFile);
Patients patients = (Patients)u.unmarshal(fis);
for (Patient p: patients.getPatient()) {
System.out.printf("ID: %s\n", p.getId());
System.out.printf("NAME: %s\n", p.getName());
System.out.printf("DIAGNOSIS: %s\n\n",
p.getDiagnosis());
}
}
If you run the sample code on the chapter20/recipe20_6/patients.xml
file and use the org.java8recipes.chapter20 context, the application will
print the following to the console as it iterates over the Patient object list:
ID: 1
NAME: John Smith
DIAGNOSIS: Common Cold
ID: 2
NAME: Jane Doe
DIAGNOSIS: Broken ankle
ID: 3
NAME: Jack Brown
DIAGNOSIS: Food allergy
Note The previous output comes directly from instances of the Java Patient class
that was created from XML representations. The code does not print the contents of the
XML file directly. Instead, it prints the contents of the Java bindings after the XML has
been marshalled into appropriate Java binding instances.
How It Works
Search WWH ::




Custom Search