SpringBoot读取XML文件数据

创建一个需要读取的XML文件数据


    
    
    
    
    

建立POJO对象,将XML数据转化为POJO对象数据

@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlRootElement(name = "d")
@XmlAccessorType(XmlAccessType.FIELD)
public class City {
    @XmlAttribute(name = "d1")
    private String cityId;
    @XmlAttribute(name = "d2")
    private String cityName;
    @XmlAttribute(name = "d3")
    private String cityCode;
    @XmlAttribute(name = "d4")
    private String province;
}
  •  @XmlRootElement申明Xml的根元素
  • @XmlAttribute申明Xml根元素中的属性名
  • @XmlAccessorType申明访问的类型是字段
@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlRootElement(name = "c")
@XmlAccessorType(XmlAccessType.FIELD)
public class CityList {

    @XmlElement(name = "d")
    private List cityLst;

}
  • @XmlElement表示字段映射的Xml中的元素 

创建一个XML解析工具类

public class XmlBuilder {

    /**
     * 将XML转为指定的POJO对象
     *
     * @param clazz 需要转换的类
     * @param xmlStr xml数据
     * @return
     */
    public static Object xmlStrToObject(Class clazz, String xmlStr) throws Exception {
        Object xmlObject = null;
        Reader reader = null;
        //利用JAXBContext将类转为一个实例
        JAXBContext context = JAXBContext.newInstance(clazz);
        //XMl 转为对象的接口
        Unmarshaller unmarshaller = context.createUnmarshaller();
        reader = new StringReader(xmlStr);
        xmlObject = unmarshaller.unmarshal(reader);
        if (reader != null) {
            reader.close();
        }
        return xmlObject;
    }
}

创建接口和实现类

/**
 * 城市数据接口
 */
public interface CityDataService {

    List listCity() throws Exception;
}
@Service
public class CityDataServiceImpl implements CityDataService {

    @Override
    public List listCity() throws Exception {
        //读取Resource目录下的XML文件
        Resource resource = new ClassPathResource("cityList.xml");
        //利用输入流获取XML文件内容
        BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(), "UTF-8"));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        br.close();
        //XML转为JAVA对象
        CityList cityList = (CityList) XmlBuilder.xmlStrToObject(CityList.class, buffer.toString());
        return cityList.getCityLst();
    }
}

 

你可能感兴趣的:(SpringBoot)