Java 读取XML 并转为JAVA对象

本文介绍了如何使用Java读取ClassPath下的XML文件,并通过JAXB将XML内容转换为StatusEntity Java对象。重点讲解了使用ClassPathResource和JAXBContext进行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;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值