当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
用JAXB实现JAVA对象与XML文件的绑定
发布时间:2010/8/23 10:30:31 来源:城市学习网 编辑:ziteng
  1.用JAXB可以实现JAVA对象与XML文件的绑定。可以直接将对象序列化到XML文件中。
  需要jaxb-api-2.1.jar支持
  2.使用方法:首先定义对象,如下面对象
  @XmlRootElement(name = "company")
  public class Company {
  @XmlElement(name = "employee")
  private List<Employee> employees;
  @XmlTransient
  public List<Employee> getEmployees() {
  return employees;
  }
  public void setEmployees(List<Employee> employees) {
  this.employees = employees;
  }
  public void addEmployee(Employee employee) {
  if (employees == null) {
  employees = new ArrayList<Employee>();
  }
  employees.add(employee);
  }
  }
  其中@XmlRootElement(name = "company")为注释,表示该Company对象对应XML文件中的根节点company,
  而@XmlElement(name = "employee")说明对应imployee元素。
  @XmlType
  public class Employee {
  @XmlElement(name = "name")
  private String name;
  @XmlElement(name = "id")
  private String id;
  @XmlTransient
  public String getId() {
  return id;
  }
  public void setId(String id) {
  this.id = id;
  } [NextPage]   @XmlTransient
  public String getName() {
  return name;
  }
  public void setName(String name) {
  this.name = name;
  }
  }
  注意要把@XmlTransient放在get()方法前面,否则可能会出现导致运行报错:
  Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:
  2 counts of IllegalAnnotationExceptions
  3.需要建一个文件jaxb.index,里面的内容为类的名字,如Company
  4.读写XML文件时
  JAXBContext jc = JAXBContext.newInstance("test.xml");
  Unmarshaller unmarshaller = jc.createUnmarshaller();
  Marshaller marshaller = jc.createMarshaller();
  // 写入文件,xmlFile为文件名
  FileOutputStream fout = new FileOutputStream(xmlFile);
  OutputStreamWriter streamWriter = new OutputStreamWriter(fout);
  // 文件写入格式
  OutputFormat outputFormat = new OutputFormat();
  outputFormat.setIndent(4);
  outputFormat.setLineSeparator(System.getProperty("line.separator"));
  XMLSerializer xmlSerializer = new XMLSerializer(streamWriter, outputFormat);
  marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
  marshaller.marshal(company, xmlSerializer);
  // 读取文件
  Company company = (Company) unmarshaller.unmarshal(xmlFile);
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved