打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
用JAXB实现JAVA对象与XML文件的绑定

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;
  }
 @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);
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用jaxb将XML转化为JAVA BEAN
Jaxb笔记
.NET中XML序列化的总结
.NET实体类序列化方法
为什么需要序列化,以及序列化的一些操作【收录】
JDK6的新特性之二:使用JAXB2来实现对象与XML之间的映射
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服