Java 怎么解组是将数据格式(XML)转换为对象的内存表示形式

2019年7月22日22:37:01Java 怎么解组是将数据格式(XML)转换为对象的内存表示形式已关闭评论 529 1466字阅读4分53秒

1.简介

Java 怎么解组是将数据格式(XML)转换为对象的内存表示形式?——请看下文。

2.示例代码

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

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