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
@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);= (Company) unmarshaller.unmarshal(XMLFile);