read Xml file with JAXB

前端 未结 2 551
隐瞒了意图╮
隐瞒了意图╮ 2021-01-02 16:20

I want to read a xml file (like below) but I get an Execption. Could you please help me how can I fix this problem?



        
2条回答
  •  一生所求
    2021-01-02 16:49

    When you describing an XML model, you need to begin with a root entity (in your case it's the element).

    @XmlRootElement(name="config")
    class Config implements Serializable {
       private Log log;
       private Env env;
    
       @XmlElement(name="log")
       public Log getLog() {
          return this.log;
       }
    
       @XmlElement(name="env")
       public Env getEnv() {
          return this.env;
       }
    
       // Setters are omitted
    }
    

    And then you parse the XML like the following:

    JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Config config = (Config) jaxbUnmarshaller.unmarshal(file);
    if (config != null && config.getLog() != null) {
       customer = config.getLog().getProperties();
    }
    

提交回复
热议问题