JAXB List Tag creating inner class

前端 未结 5 1142
无人及你
无人及你 2020-12-16 17:29

So we have an XSD type in the form:


    
        
            

        
5条回答
  •  借酒劲吻你
    2020-12-16 17:52

    You could do the following:

    package example;
    
    import java.util.List;
    
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlElementWrapper;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name="Foo")
    public class Foo {
    
        private List bar;
    
        public List getBar() {
            return bar;
        }
    
        @XmlElementWrapper(name="Bars")
        @XmlElement(name="Bar")
        public void setBar(List bar) {
            this.bar = bar;
        }
    
    }
    

    and

    package example;
    
    public class Bar {
    
    }
    

    Then you can process your XML using the following code;

    package example;
    
    import java.io.File;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Foo.class);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            Foo foo = (Foo) unmarshaller.unmarshal(new File("src/forum128/input.xml"));
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(foo, System.out);
        }
    }
    

提交回复
热议问题