熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

用JAXB實現JAVA對象與XML文件的綁定

2022-06-13   來源: Java核心技術 

  用JAXB可以實現JAVA對象與XML文件的綁定可以直接將對象序列化到XML文件中

  需要jaxbapijar支持

  使用方法首先定義對象如下面對象

  @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) {

  thisemployees = employees;

  }

  public void addEmployee(Employee employee) {

  if (employees == null) {

  employees = new ArrayList<Employee>();

  }

  employeesadd(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) {

  thisid = id;

  }

  @XmlTransient

  public String getName() {

  return name;

  }

  public void setName(String name) {

  thisname = name;

  }

  }

  注意要把@XmlTransient放在get()方法前面否則可能會出現導致運行報錯

  Exception in thread main comsunxmlinternalbindvruntimeIllegalAnnotationsException:

   counts of IllegalAnnotationExceptions

  需要建一個文件jaxbindex裡面的內容為類的名字如Company

  讀寫XML文件時

  JAXBContext jc = JAXBContextnewInstance(testxml);

  Unmarshaller unmarshaller = jccreateUnmarshaller();

  Marshaller marshaller = jccreateMarshaller();

  // 寫入文件xmlFile為文件名

  FileOutputStream fout = new FileOutputStream(xmlFile);

  OutputStreamWriter streamWriter = new OutputStreamWriter(fout);

  // 文件寫入格式

  OutputFormat outputFormat = new OutputFormat();

  outputFormatsetIndent();

  outputFormatsetLineSeparator(SystemgetProperty(lineseparator));

  XMLSerializer xmlSerializer = new XMLSerializer(streamWriter outputFormat);

  marshallersetProperty(MarshallerJAXB_ENCODING UTF);

  marshallermarshal(company xmlSerializer);

  // 讀取文件

  Company company = (Company) unmarshallerunmarshal(xmlFile);


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26719.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.