JAXB Unmarshalling @XmlAnyElement

前端 未结 1 1109
一个人的身影
一个人的身影 2021-01-12 18:07

I have created three JAXB class : Home , Person , Animal . Java Class Home have variable List any that may contain Person and/or Ani
1条回答
  •  再見小時候
    2021-01-12 18:25

    You need to add @XmlRootElement on the classes you want to appear as instances in the field/property you have annotated with @XmlAnyElement(lax=true).

    Java Model

    Home

    import java.util.List;
    import javax.xml.bind.annotation.*;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Home {
        @XmlAnyElement(lax = true)
        protected List any;
    
        //setter getter also implemented
    }
    
    
    

    Person

    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name="Person")
    public class Person {
    

    }

    Animal

    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name="Animal")
    public class Animal {
    
    }
    

    Demo Code

    input.xml

    
    
        
        
        
    
    

    Demo

    import javax.xml.bind.*;
    import javax.xml.transform.stream.StreamSource;
    
    public class Demo {
    
        public static void main(String[] args) throws JAXBException {
            JAXBContext jc = JAXBContext.newInstance(Home.class, Person.class, Animal.class);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            StreamSource xml = new StreamSource("src/forum20329510/input.xml");
            Home home = unmarshaller.unmarshal(xml, Home.class).getValue();
    
            for(Object object : home.any) {
                System.out.println(object.getClass());
            }
        }
    
    }
    

    Output

    class forum20329510.Person
    class forum20329510.Animal
    class forum20329510.Person
    

    For More Information

    • http://blog.bdoughan.com/2012/12/jaxbs-xmlanyelementlaxtrue-explained.html

    0 讨论(0)
    提交回复
    热议问题