如何将XML转换为Java对象

怼烎@ 2021-06-12 15:16 991阅读 0赞

1.首先创建citylist.xml文件,放在resource目录下,文件内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <c c1="0">
  3. <d d1="101280101" d2="广州" d3="guangzhou" d4="广东"/>
  4. <d d1="101280102" d2="番禺" d3="panyu" d4="广东"/>
  5. <d d1="101280103" d2="从化" d3="conghua" d4="广东"/>
  6. </c>

2.创建与xml文件中的元素相对应的Bean,分别是CityList和City。
CityList.java

  1. /**
  2. * @desc 城市列表
  3. */
  4. @XmlRootElement(name="c") //声明为xml的根元素c
  5. @XmlAccessorType(XmlAccessType.FIELD) //通过字段来访问
  6. public class CityList implements Serializable {
  7. @XmlElement(name="d") //映射的xml元素
  8. private List<City> cityList;
  9. public List<City> getCityList() {
  10. return cityList;
  11. }
  12. public void setCityList(List<City> cityList) {
  13. this.cityList = cityList;
  14. }
  15. }

City.java

  1. /**
  2. * @desc 城市信息 解析citylist.xml获取
  3. */
  4. @XmlRootElement(name="d") //声明为xml的根元素d
  5. @XmlAccessorType(XmlAccessType.FIELD) //通过字段来访问
  6. public class City implements Serializable {
  7. @XmlAttribute(name="d1") //映射的xml属性
  8. private String cityId;
  9. @XmlAttribute(name="d2")
  10. private String cityName;
  11. @XmlAttribute(name="d3")
  12. private String cityCode;
  13. @XmlAttribute(name="d4")
  14. private String province;
  15. public String getCityId() {
  16. return cityId;
  17. }
  18. public void setCityId(String cityId) {
  19. this.cityId = cityId;
  20. }
  21. public String getCityName() {
  22. return cityName;
  23. }
  24. public void setCityName(String cityName) {
  25. this.cityName = cityName;
  26. }
  27. public String getCityCode() {
  28. return cityCode;
  29. }
  30. public void setCityCode(String cityCode) {
  31. this.cityCode = cityCode;
  32. }
  33. public String getProvince() {
  34. return province;
  35. }
  36. public void setProvince(String province) {
  37. this.province = province;
  38. }
  39. }

3.读取xml文件,将其内容转换为字符串。

  1. //读取xml文件
  2. Resource resource=new ClassPathResource("citylist.xml");
  3. BufferedReader reader=new BufferedReader(new InputStreamReader(resource.getInputStream(),"utf-8"));
  4. StringBuffer buffer=new StringBuffer();
  5. String line="";
  6. while((line=reader.readLine())!=null){
  7. buffer.append(line);
  8. }
  9. reader.close();

4.将CityList.class和buffer.toString()传入到以下方法的形参中,实现XML的对象转换。

  1. /**
  2. * 将XML转为指定的POJO对象
  3. * @param clazz
  4. * @param xmlStr
  5. * @return
  6. */
  7. public static Object xmlStrToObject(Class<?> clazz,String xmlStr) throws Exception {
  8. Object xmlObject=null;
  9. Reader reader=null;
  10. JAXBContext context=JAXBContext.newInstance(clazz);
  11. //xml转为对象的接口
  12. Unmarshaller unmarshaller=context.createUnmarshaller();
  13. reader=new StringReader(xmlStr);
  14. xmlObject=unmarshaller.unmarshal(reader);
  15. if(null!=reader){
  16. reader.close();
  17. }
  18. return xmlObject;
  19. }

发表评论

表情:
评论列表 (有 0 条评论,991人围观)

还没有评论,来说两句吧...

相关阅读