1.首先创建citylist.xml文件,放在resource目录下,文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<c c1="0">
<d d1="101280101" d2="广州" d3="guangzhou" d4="广东"/>
<d d1="101280102" d2="番禺" d3="panyu" d4="广东"/>
<d d1="101280103" d2="从化" d3="conghua" d4="广东"/>
</c>
2.创建与xml文件中的元素相对应的Bean,分别是CityList和City。
CityList.java
/**
* @desc 城市列表
*/
@XmlRootElement(name="c") //声明为xml的根元素c
@XmlAccessorType(XmlAccessType.FIELD) //通过字段来访问
public class CityList implements Serializable {
@XmlElement(name="d") //映射的xml元素
private List<City> cityList;
public List<City> getCityList() {
return cityList;
}
public void setCityList(List<City> cityList) {
this.cityList = cityList;
}
}
City.java
/**
* @desc 城市信息 解析citylist.xml获取
*/
@XmlRootElement(name="d") //声明为xml的根元素d
@XmlAccessorType(XmlAccessType.FIELD) //通过字段来访问
public class City implements Serializable {
@XmlAttribute(name="d1") //映射的xml属性
private String cityId;
@XmlAttribute(name="d2")
private String cityName;
@XmlAttribute(name="d3")
private String cityCode;
@XmlAttribute(name="d4")
private String province;
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
}
3.读取xml文件,将其内容转换为字符串。
//读取xml文件
Resource resource=new ClassPathResource("citylist.xml");
BufferedReader reader=new BufferedReader(new InputStreamReader(resource.getInputStream(),"utf-8"));
StringBuffer buffer=new StringBuffer();
String line="";
while((line=reader.readLine())!=null){
buffer.append(line);
}
reader.close();
4.将CityList.class和buffer.toString()传入到以下方法的形参中,实现XML的对象转换。
/**
* 将XML转为指定的POJO对象
* @param clazz
* @param xmlStr
* @return
*/
public static Object xmlStrToObject(Class<?> clazz,String xmlStr) throws Exception {
Object xmlObject=null;
Reader reader=null;
JAXBContext context=JAXBContext.newInstance(clazz);
//xml转为对象的接口
Unmarshaller unmarshaller=context.createUnmarshaller();
reader=new StringReader(xmlStr);
xmlObject=unmarshaller.unmarshal(reader);
if(null!=reader){
reader.close();
}
return xmlObject;
}