Java 怎么使用JAXB构建XML文档

2019年7月22日22:36:58Java 怎么使用JAXB构建XML文档已关闭评论 422 1287字阅读4分17秒

1.简介

Java 怎么使用JAXB构建XML文档?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
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);
    }
    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;
  }
  
}

 
继续阅读
编程十万个怎么办