jaxb是一种把java类和xml文件转换的jar包.
在JDK1.6后加入了,下面是小demo:
第一步,pojo类
package cn.com.JAXB;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @Description
* @auther lenovo
* @create 2019-11-17 18:36
*/
/**
* 转换至xml对象的java类
*/
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlElement
public void setId(int id) {
this.id = id;
}
}
第二步,把XML文件写入磁盘中.
package cn.com.JAXB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
/**
* @Description
* @auther lenovo
* @create 2019-11-17 18:41
*/
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(118);
customer.setName("baby");
customer.setAge(19);
try {
//把java类写入磁盘中,以xml的形式
File file = new File("D:\\File-Copy\\JAXB\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
第三步,控制台结果: