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;
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java中的JAXB(Java Architecture for XML Binding)库来将Java对象转换为XML文件。 JAXB提供了将Java类转换为XML文档和从XML文档中读取Java类的机制。下面是一个示例代码片段: ``` import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; public class ObjectToXML { public static void main(String[] args) throws Exception { //创建需要转换为XMLjava对象 Employee employee = new Employee(); employee.setId(1001); employee.setName("张三"); employee.setAge(25); //将Java对象转换为XML文件 JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(employee, new File("employee.xml")); //将XML文件转换为Java对象 Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Employee unmarshalledEmployee = (Employee) unmarshaller.unmarshal(new File("employee.xml")); System.out.println(unmarshalledEmployee.getId() + " " + unmarshalledEmployee.getName() + " " + unmarshalledEmployee.getAge()); } } ``` 该示例创建了一个名为Employee的Java类,具有id、name和age属性。然后使用JAXBContext创建了Marshaller和Unmarshaller,分别将Java对象转换为XML并将XML转换为Java对象。运行该示例后,将生成一个名为“employee.xml”的XML文件,并在控制台打印转换后的Java对象的属性值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值