使用JAXB可以快速完成Java类到XML的映射,方便XML文件的解析与生成。
常用注解
@ XmlRootElement(name = "Country")将Java类或枚举类型映射成XML中根元素,设置name属性的值可指定义根元素名称,不设置则默认为类型首字母小写的名称。
@ XmlType(propOrder = {"name", "capital", "population", "foundationTime"})
将Java类后枚举类型映射到XML模式类型,设置propOrder可以指定生成XML中各元素的先后顺序。
@ XmlElement(name = "CFoundationTime")
将JavaBean中的字段值映射到XML元素,设置name属性的值可指定XML元素的名称。
@ XmlAttribute(name = "CRank", required = false)
将JavaBean中的字段映射到XML中元素的属性,设置name属性的值可指定xml中元素属性的名称;
至于required属性,官方文档是说指定 XML 模式属性是可选的还是必需的,不是特别理解。
@ XmlElementWrapper(name = "CountryWrapper")
为集合生成xml包装器元素,简单来讲就是使XML元素更有层次感,更美观,该注解只能用在集合上。
例子
1、类结构如下
Country与Countries为映射对象;
JAXBUtils提供读写XML的方法;
JAXBXMLTest提供读写测试方法;
2、各个类如下
Country类:
package com.jaxb;
import javax.xml.bind.annotation.*;
@XmlType(propOrder = {"name", "capital", "population", "foundationTime"})
@XmlRootElement(name = "Country")
public class Country {
private int population;
private String name;
private String capital;
private int rank;
private String foundationTime;
public String getFoundationTime() {
return foundationTime;
}
@XmlElement(name = "CFoundationTime")
public void setFoundationTime(String foundationTime) {
this.foundationTime = foundationTime;
}
public int getPopulation() {
return population;
}
@XmlElement(name = "CPopulation")
public void setPopulation(int population) {
this.population = population;
}
public String getName() {
return name;
}
@XmlElement(name = "CName")
public void setName(String name) {
this.name = name;
}
public String getCapital() {
return capital;
}
@XmlElement(name = "CCapital")
public void setCapital(String capital) {
this.capital = capital;
}
public int getRank() {
return rank;
}
@XmlAttribute(name = "CRank", required = true)
public void setRank(int rank) {
this.rank = rank;
}
@Override
public String toString() {
return "Country=[Name=" + this.getName() +
", Capital=" + this.getCapital() +
", Population=" + this.getPopulation() +
", FoundationTime=" + this.getFoundationTime() + "]";
}
}
Countries类:
package com.jaxb;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "Countries")
public class Countries {
private List<Country> countries;
public List<Country> getCountries() {
return countries;
}
@XmlElementWrapper(name = "CountryWrapper")
@XmlElement(name = "Country")
public void setCountries(List<Country> countries) {
this.countries = countries;
}
@Override
public String toString() {
return "Countries=[" + this.getCountries() + "]";
}
}
JAXBUtils类:
package com.jaxb;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public class JAXBUtils {
public static void writeXML(Object obj, File path, Class... clazz) throws JAXBException {
JAXBContext jctx = JAXBContext.newInstance(clazz);
Marshaller marshaller = jctx.createMarshaller();
// 格式化输出,设置换行和缩进,不设置则会显示在一行
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(obj, path);
// 设置控制台输出
marshaller.marshal(obj, System.out);
}
public static Object readXML(File path, Class... clazz) throws JAXBException {
JAXBContext jctx = JAXBContext.newInstance(clazz);
Unmarshaller unMarshaller = jctx.createUnmarshaller();
Object obj = unMarshaller.unmarshal(path);
return obj;
}
}
JAXBXMLTest类:
package com.jaxb;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
public class JAXBXMLTest {
private static final String XML_PATH_COUNTRY = "./Country.xml";
private static final String XML_PATH_COUNTRIES = "./Countries.xml";
public static void main(String[] args) throws JAXBException {
Country china = new Country();
china.setName("中国");
china.setCapital("北京");
china.setPopulation(1400000000);
china.setRank(25);
String fTimeChina = LocalDate.of(1949, 10, 1).toString();
china.setFoundationTime(fTimeChina);
Country america = new Country();
america.setName("United States of America");
america.setCapital("New York");
america.setPopulation(300000000);
america.setRank(11);
String fTimeAmerica = LocalDate.of(1776, 7, 4).toString();
america.setFoundationTime(fTimeAmerica);
File xmlFile = new File(XML_PATH_COUNTRY);
File xmlFile1 = new File(XML_PATH_COUNTRIES);
System.out.println("\n【写入到" + XML_PATH_COUNTRY + "】");
JAXBUtils.writeXML(china, xmlFile, Country.class);
System.out.println("\n【写入list到" + XML_PATH_COUNTRIES + "】");
Countries countries = new Countries();
ArrayList<Country> list = new ArrayList<>();
list.add(china);
list.add(america);
countries.setCountries(list);
JAXBUtils.writeXML(countries, xmlFile1, Countries.class);
System.out.println("\n【从" + XML_PATH_COUNTRIES + "中读取】");
Countries countriesRead = (Countries) JAXBUtils.readXML(xmlFile1, Countries.class, Country.class);
System.out.println(countriesRead);
System.out.println("\n【从" + XML_PATH_COUNTRY + "中读取】");
Country countryRead = (Country) JAXBUtils.readXML(xmlFile, Country.class);
System.out.println(countryRead);
}
}
运行测试类,结果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/2c9e22eb5cb7148832a47bfab3564684.png)