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