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; }

 

posted @ 2020-07-24 10:38  千夜大魔王  阅读(2223)  评论(0编辑  收藏  举报