【XML】使用javax.xml.bind包实现bean-xml互转
第一步:说明:
JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。该过程中,JAXB也提供了将XML实例文档反向生成Java对象树的方法,并能将Java对象树的内容重新写到XML实例文档。从另一方面来讲,JAXB提供了快速而简便的方法将XML模式绑定到Java表示,从而使得Java开发者在Java应用程序中能方便地结合XML数据和处理函数。
第二步:相关的重要Class、Interface和Annotation
A、JDK中JAXB相关的重要Class和Interface
- JAXBContext类,是应用的入口,用于管理XML/Java绑定信息。
- Marshaller接口,将Java对象序列化为XML数据。
- Unmarshaller接口,将XML数据反序列化为Java对象。
B、 JDK中JAXB相关的重要注解(Annotation)
- @XmlRootElement:根节点,将Java类或枚举类型映射到XML元素。
- @XmlAttribute:该属性作为xml的attribute,将Java类的一个属性映射到与属性同名的一个XML元素。
- @XmlElement:该属性作为xml的element,且可以增加属性(name="NewElementName"),那么生成的xml串的elment的标签是NewElementName
- @XmlAccessorType(XmlAccessType.PROPERTY):意思是 只有属性(有get和set方法才是属性,没有get和set方法的不是属性)才能被转换成 xml 中的标签。@XmlAccessorType(XmlAccessType.FIELD) ,控制字段或属性的序列化。FIELD表示JAXB将自动绑定Java类中的每个非静态的(static)、非瞬态的(由@XmlTransient标注)字段到XML。
- @XmlAccessorOrder,控制JAXB 绑定类中属性和字段的排序。
- @XmlJavaTypeAdapter,使用定制的适配器(即扩展抽象类XmlAdapter并覆盖marshal()和unmarshal()方法),以序列化Java类为XML。
- @XmlElementWrapper ,对于数组或集合(即包含多个元素的成员变量),生成一个包装该数组或集合的XML元素(称为包装器)。
- @XmlType注解标注xml生成顺序,默认情况下,Jaxb编组出来的xml中的字段顺序是随机的,你可以使用@XmlType的propOrder属性来指定序列化的顺序。
注:
1.对于@XmlElementWrapper标注的属性,不能出现在@XmlType的propOrder列表中。
2.对于所有@XmlElement标注过的属性,必须出现在@XmlType的propOrder列表中。
第三步:使用demo
目录结构:
定义一个User类:
-
package xmlUtil;
-
-
import java.io.Serializable;
-
import java.util.Date;
-
import java.util.List;
-
-
import javax.xml.bind.annotation.*;
-
-
/**
-
* @Author: 轻狂书生FS
-
* @Description:
-
* @CreateDate: 2019/3/29 10:04
-
* @Version: 1.0
-
*/
-
@XmlAccessorType(XmlAccessType.FIELD)
-
// XML文件中的根标识
-
@XmlRootElement(name = "User")
-
public class User implements Serializable {
-
private static final long serialVersionUID = 1L;
-
-
@XmlAttribute(name = "xmnl")
-
private final String xmnl="www.baidu.com";
-
-
// 用户Id
-
@XmlElement(name = "UserId")
-
private int userId;
-
// 用户名
-
@XmlElement(name = "UserName")
-
private String userName;
-
// 用户密码
-
@XmlElement(name = "Password")
-
private String password;
-
// 用户生日
-
@XmlElement(name = "Birthday")
-
private Date birthday;
-
// 用户钱包
-
@XmlElement(name = "Money")
-
private double money;
-
//用户地址
-
@XmlElementWrapper(name = "AddressList")
-
@XmlElement(name = "Address")
-
private List<Address> addressList;
-
//用户电脑
-
@XmlElement(name = "Computers")
-
private List<Computer> computers;
-
-
public List<Computer> getComputers() {
-
return computers;
-
}
-
-
public void setComputers(List<Computer> computers) {
-
this.computers = computers;
-
}
-
-
public List<Address> getAddressList() {
-
return addressList;
-
}
-
-
public void setAddressList(List<Address> addressList) {
-
this.addressList = addressList;
-
}
-
-
public User() {
-
super();
-
}
-
-
public User(int userId, String userName, String password, Date birthday,
-
double money) {
-
super();
-
this.userId = userId;
-
this.userName = userName;
-
this.password = password;
-
this.birthday = birthday;
-
this.money = money;
-
}
-
-
public int getUserId() {
-
return userId;
-
}
-
-
public void setUserId(int userId) {
-
this.userId = userId;
-
}
-
-
public String getUserName() {
-
return userName;
-
}
-
-
public void setUserName(String userName) {
-
this.userName = userName;
-
}
-
-
public String getPassword() {
-
return password;
-
}
-
-
public void setPassword(String password) {
-
this.password = password;
-
}
-
-
public Date getBirthday() {
-
return birthday;
-
}
-
-
public void setBirthday(Date birthday) {
-
this.birthday = birthday;
-
}
-
-
public double getMoney() {
-
return money;
-
}
-
-
public void setMoney(double money) {
-
this.money = money;
-
}
-
-
@Override
-
public String toString() {
-
return "User{" +
-
"xmnl='" + xmnl + '\'' +
-
", userId=" + userId +
-
", userName='" + userName + '\'' +
-
", password='" + password + '\'' +
-
", birthday=" + birthday +
-
", money=" + money +
-
", addressList=" + addressList +
-
", computers=" + computers +
-
'}';
-
}
-
}
定义一个Address类
-
package xmlUtil;
-
-
import javax.xml.bind.annotation.XmlType;
-
import java.io.Serializable;
-
-
/**
-
* @Author: 轻狂书生FS
-
* @Description:
-
* @CreateDate: 2019/3/29 10:29
-
* @Version: 1.0
-
*/
-
// 控制JAXB 绑定类中属性和字段的排序
-
@XmlType(propOrder = {
-
"city",
-
"province",
-
})
-
public class Address implements Serializable {
-
-
private String province;
-
-
private String city;
-
-
public String getProvince() {
-
return province;
-
}
-
-
public void setProvince(String province) {
-
this.province = province;
-
}
-
-
public String getCity() {
-
return city;
-
}
-
-
public void setCity(String city) {
-
this.city = city;
-
}
-
-
public Address(String province, String city) {
-
this.province = province;
-
this.city = city;
-
}
-
-
public Address() {
-
}
-
}
定义一个Computer类
-
package xmlUtil;
-
-
import java.io.Serializable;
-
import java.util.Date;
-
-
import javax.xml.bind.annotation.XmlAccessType;
-
import javax.xml.bind.annotation.XmlAccessorType;
-
import javax.xml.bind.annotation.XmlRootElement;
-
import javax.xml.bind.annotation.XmlType;
-
-
/**
-
* @Author: 轻狂书生FS
-
* @Description:
-
* @CreateDate: 2019/3/29 10:44
-
* @Version: 1.0
-
*/
-
@XmlAccessorType(XmlAccessType.FIELD)
-
@XmlRootElement(name = "Computer")
-
@XmlType(propOrder = { "brandName", "price" })
-
public class Computer implements Serializable {
-
private static final long serialVersionUID = 1L;
-
-
// 品牌名
-
private String brandName;
-
// 价格
-
private double price;
-
-
public Computer() {
-
super();
-
}
-
-
public Computer( String brandName,double price) {
-
super();
-
this.brandName = brandName;
-
this.price = price;
-
}
-
-
public String getBrandName() {
-
return brandName;
-
}
-
-
public void setBrandName(String brandName) {
-
this.brandName = brandName;
-
}
-
-
public double getPrice() {
-
return price;
-
}
-
-
public void setPrice(double price) {
-
this.price = price;
-
}
-
-
@Override
-
public String toString() {
-
return "Computer{" +
-
"brandName='" + brandName + '\'' +
-
", price=" + price +
-
'}';
-
}
-
}
此时给出最重要的进行Java对象和XML文件相互操作的核心代码XMLUtil.java,其中有着两种方式进行转换,一种是转换成对象和string类型的xml转换,一种是对象和xml文件进行转换。
-
package xmlUtil;
-
-
import java.io.FileNotFoundException;
-
import java.io.FileReader;
-
import java.io.FileWriter;
-
import java.io.IOException;
-
import java.io.StringReader;
-
import java.io.StringWriter;
-
-
import javax.xml.bind.JAXBContext;
-
import javax.xml.bind.JAXBException;
-
import javax.xml.bind.Marshaller;
-
import javax.xml.bind.Unmarshaller;
-
-
/**
-
* 封装了XML转换成object,object转换成XML的代码
-
*
-
* @author Steven
-
*
-
*/
-
public class XMLUtil {
-
/**
-
* 将对象直接转换成String类型的 XML输出
-
*
-
* @param obj
-
* @return
-
*/
-
public static String convertToXml(Object obj) {
-
// 创建输出流
-
StringWriter sw = new StringWriter();
-
try {
-
// 利用jdk中自带的转换类实现
-
JAXBContext context = JAXBContext.newInstance(obj.getClass());
-
-
Marshaller marshaller = context.createMarshaller();
-
// 格式化xml输出的格式
-
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
-
Boolean.TRUE);
-
// 将对象转换成输出流形式的xml
-
marshaller.marshal(obj, sw);
-
} catch (JAXBException e) {
-
e.printStackTrace();
-
}
-
return sw.toString();
-
}
-
-
/**
-
* 将对象根据路径转换成xml文件
-
*
-
* @param obj
-
* @param path
-
* @return
-
*/
-
public static void convertToXml(Object obj, String path) {
-
try {
-
// 利用jdk中自带的转换类实现
-
JAXBContext context = JAXBContext.newInstance(obj.getClass());
-
-
Marshaller marshaller = context.createMarshaller();
-
// 格式化xml输出的格式
-
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
-
Boolean.TRUE);
-
// 将对象转换成输出流形式的xml
-
// 创建输出流
-
FileWriter fw = null;
-
try {
-
fw = new FileWriter(path);
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
marshaller.marshal(obj, fw);
-
} catch (JAXBException e) {
-
e.printStackTrace();
-
}
-
}
-
-
@SuppressWarnings("unchecked")
-
/**
-
* 将String类型的xml转换成对象
-
*/
-
public static Object convertXmlStrToObject(Class clazz, String xmlStr) {
-
Object xmlObject = null;
-
try {
-
JAXBContext context = JAXBContext.newInstance(clazz);
-
// 进行将Xml转成对象的核心接口
-
Unmarshaller unmarshaller = context.createUnmarshaller();
-
StringReader sr = new StringReader(xmlStr);
-
xmlObject = unmarshaller.unmarshal(sr);
-
} catch (JAXBException e) {
-
e.printStackTrace();
-
}
-
return xmlObject;
-
}
-
-
@SuppressWarnings("unchecked")
-
/**
-
* 将file类型的xml转换成对象
-
*/
-
public static Object convertXmlFileToObject(Class clazz, String xmlPath) {
-
Object xmlObject = null;
-
try {
-
JAXBContext context = JAXBContext.newInstance(clazz);
-
Unmarshaller unmarshaller = context.createUnmarshaller();
-
FileReader fr = null;
-
try {
-
fr = new FileReader(xmlPath);
-
} catch (FileNotFoundException e) {
-
e.printStackTrace();
-
}
-
xmlObject = unmarshaller.unmarshal(fr);
-
} catch (JAXBException e) {
-
e.printStackTrace();
-
}
-
return xmlObject;
-
}
-
}
测试类:
-
package xmlUtil;
-
-
-
import java.util.ArrayList;
-
import java.util.Date;
-
import java.util.List;
-
-
/**
-
* @Author: 轻狂书生FS
-
* @Description:
-
* @CreateDate: 2019/3/29 10:31
-
* @Version: 1.0
-
*/
-
public class Test {
-
public static void main(String[] args) {
-
// 创建需要转换的对象
-
User user = new User(1, "Steven", "@sun123", new Date(), 1000.0);
-
-
List<Address> addressList = new ArrayList<>();
-
Address address1 = new Address("山东省","菏泽市");
-
Address address2 = new Address("上海市","浦东新区");
-
Address address3 = new Address("浙江省","杭州");
-
addressList.add(address1);
-
addressList.add(address2);
-
addressList.add(address3);
-
user.setAddressList(addressList);
-
-
System.out.println("---将对象转换成string类型的xml Start---");
-
// 将对象转换成string类型的xml
-
String str = XMLUtil.convertToXml(user);
-
// 输出
-
System.out.println(str);
-
System.out.println("---将对象转换成string类型的xml End---");
-
System.out.println();
-
}
-
}
运行结果:
请仔细体会,xml和注解之间的关系。
本文参考:https://blog.csdn.net/songdeitao/article/details/17304395
文章来源: blog.csdn.net,作者:轻狂书生FS,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/LookForDream_/article/details/88884316
- 点赞
- 收藏
- 关注作者
评论(0)