如何将XML转换为Java对象

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wunianisme

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值