Building an XML Document with JAXB - Java XML

Java examples for XML:JAXB

Description

Building an XML Document with JAXB

Demo Code

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.LinkedList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {
  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println("Usage: java Main <xmlfile> <context>");
      System.exit(1);/*www .j  a v  a 2s.c o m*/
    }
    Main app = new Main();
    try {
      app.run(args[0], args[1]);
    } catch (JAXBException ex) {
      ex.printStackTrace();
    } catch (FileNotFoundException ex) {
      ex.printStackTrace();
    }
  }

  public void run(String xmlFile, String context) throws JAXBException,
      FileNotFoundException {
    Patients patients = new Patients();
    List<Patient> patientList = new LinkedList<>();

    Patient p = new Patient();
    p.setId(1);
    p.setName("A");
    p.setDiagnosis("B");

    patientList.add(p);

    JAXBContext jc = JAXBContext.newInstance(context);
    Marshaller m = jc.createMarshaller();
    m.marshal(patients, new FileOutputStream(xmlFile));
  }
}

class Patients{
  
}
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;
  }
  
}

Related Tutorials