JAXB Unmarshalling @XmlAnyElement

纵饮孤独 提交于 2019-12-01 05:16:24

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<Object> 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

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <Person/>
    <Animal/>
    <Person/>
</root>

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!