Binding XML using POJO and JAXB annotations

后端 未结 2 1440
我寻月下人不归
我寻月下人不归 2020-12-19 22:58

I have the following xml format that i want to bind it through a POJO and using JAXB annotations. The XML format is the following:

 
   

        
相关标签:
2条回答
  • 2020-12-19 23:22

    You can do one of the following options:

    OPTION #1

    Datas

    package forum11311374;
    
    import java.util.List;
    import javax.xml.bind.annotation.*;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Datas {
    
      private List<String> data;
    
      //get/set methods
    
    }
    

    For More Information

    • http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html

    OPTION #2

    Datas

    package forum11311374;
    
    import java.util.List;
    import javax.xml.bind.annotation.*;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Datas {
    
      @XmlElement(name="data")
      private List<Data> datas;
    
      //get/set methods
    
    }
    

    Data

    package forum11311374;
    
    import javax.xml.bind.annotation.*;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Data{
    
      @XmlValue
      private String data;
    
      //get/set methods
    
    }
    

    For More Information

    • http://blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html

    The following can be used with both options:

    input.xml/Ouput

    I have updated the XML document to contain the necessary closing tags. <data>apple</data> instead of <data>apple<data>.

    <datas>
       <data>apple</data>
       <data>banana</data>
       <data>orange</data>
     </datas>
    

    Demo

    package forum11311374;
    
    import java.io.File;
    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Datas.class);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            File xml = new File("src/forum11311374/input.xml");
            Datas datas = (Datas) unmarshaller.unmarshal(xml);
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(datas, System.out);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-19 23:26

    The first option did work for me... not sure why you are getting the problem... Try this annotation...

    @XmlElements(@XmlElement(name="data", type=String.class))
    private List<String> datas; //ignore the variable name
    
    0 讨论(0)
提交回复
热议问题