Java XML转对象


直接上代码

第一步:添加一个xml转对象方法

/**
 * xml文件配置转换为对象
 *
 * @param xmlPath xml文件路径
 * @param load    java对象.Class
 * @return java对象
 * @throws JAXBException
 * @throws IOException
 */
 public static Object xmlToBean(String xmlPath, Class<?> load) throws Exception {
     JAXBContext context = JAXBContext.newInstance(load);
     Unmarshaller unmarshaller = context.createUnmarshaller();
     Object object = unmarshaller.unmarshal(new File(xmlPath));
     return object;
 }

第二步:

public static void main(String[] args) {
    //CEB622Message 是实体类,你们根据你们要转的实体类填写
  //读取文件的存放目录
    Map<String, String> path = new HashMap<String, String>();
  try {
    path = m.getPaths();//getPaths方法是自写的,本博客的另外的帖子也有,需要的可以去另外帖子拿,传送门:https://www.cnblogs.com/qydmw/p/13370501.html
     String xmlPath = path.get("read") + files[i].getName();//文件名字 Object object = null; 
        //参数是xml文件和实体类 object
= m.xmlToBean(xmlPath, CEB621Message.class); } catch (Exception e) { e.printStackTrace(); } CEB622Message ceb622Message = (CEB622Message) object; }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM