Java 读取XML 并转为JAVA对象

读取xml文件

  //读取Resource目录下的XML文件
        ClassPathResource resource = new ClassPathResource("protocols/status/" + subsystemType + ".xml");
//        Resource resource = new ClassPathResource("classpath:protocols/SubSystems.xml");
        //利用输入流获取XML文件内容
        BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder buffer = new StringBuilder();
        String line = "";
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        br.close();
         //XML转为JAVA对象
        return (StatusEntity) XmlBuilder.xmlStrToObject(StatusEntity.class, buffer.toString());

XML转JAVA对象

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.Reader;
import java.io.StringReader;

public class XmlBuilder {
    public static Object xmlStrToObject(Class<?> clazz, String xmlStr) throws Exception {
        Object xmlObject = null;
        Reader reader = null;
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        reader = new StringReader(xmlStr);
        try {
            xmlObject = unmarshaller.unmarshal(reader);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (reader != null) {
            reader.close();
        }
        return xmlObject;
    }
}

你可能感兴趣的:(Java,java,xml,开发语言)