Java examples for XML:JAXB
Unmarshalling is to convert a data format (XML) into a memory representation of the object.
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class Main { public void run(String xmlFile, String context) throws JAXBException, FileNotFoundException {/*from w ww.j av a 2 s . c o m*/ 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()); } } public static void main(String[] args) { if (args.length != 2) { System.out.printf("Usage: java Main <xmlfile> <context>\n"); System.exit(1); } Main app = new Main(); try { app.run(args[0], args[1]); } catch (JAXBException ex) { ex.printStackTrace(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } } class Patients{ List<Patient> patient; public List<Patient> getPatient() { return patient; } public void setPatient(List<Patient> patient) { this.patient = patient; } } class Patient{ private int id; private String name; private String diagnosis; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDiagnosis() { return diagnosis; } public void setDiagnosis(String diagnosis) { this.diagnosis = diagnosis; } }