实体类:
package xml; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement
public class User {
String name;
String english_name;
String age;
String sex;
String address;
String description;
public User(){} public User(String name, String english_name, String age, String sex,
String address, String description) {
this.name=name;
this.english_name=english_name;
this.age=age;
this.sex=sex;
this.address=address;
this.description=description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEnglish_name() {
return english_name;
}
public void setEnglish_name(String english_name) {
this.english_name = english_name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
} }
一.java对象转化成xml文件
package xml; import java.io.File; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller; /**
* 将类映射成xml
* @author Administrator
*
*/
public class Demo1 {
public static void main(String[] args) {
//创建xml对象,将他保存在指定位置
File file = new File("D:\\javaItem\\xml\\src\\xml\\1.xml");
//申明一个JAXBContext对象
JAXBContext jaxbContext;
try {
//指定映射的类,创建JAXBContext对象的上下文
jaxbContext = JAXBContext.newInstance(User.class);
//创建转化对象Marshaller
Marshaller m = jaxbContext.createMarshaller();
//创建xml文件中的数据
User user = new User("张三", "zhangsnan", "30", "男", "安徽合肥", "软件工程师");
//将Java类中的User对象转化到XML
m.marshal(user, file);
System.out.println("转化完成");
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
二.xml文件转化为java对象
package xml; import java.io.File; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller; public class Demo2 {
public static void main(String[] args) {
File file=new File("D:\\javaItem\\xml\\src\\xml\\1.xml");
JAXBContext jaxbContext;
try {
jaxbContext=JAXBContext.newInstance(User.class);
Unmarshaller u=jaxbContext.createUnmarshaller();
User user=(User)u.unmarshal(file);
System.out.println("姓名:"+user.getName());
System.out.println("英文名字:"+user.getEnglish_name());
System.out.println("年龄:"+user.getAge());
System.out.println("性别:"+user.getSex());
System.out.println("地址:"+user.getAddress());
System.out.println("描述:"+user.getDescription());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}