首页javajaxbJava HTML/XML - 如何使用JAXB Unmarshal @XmlAnyElement

Java HTML/XML - 如何使用JAXB Unmarshal @XmlAnyElement

我们想知道如何使用JAXB Unmarshal @XmlAnyElement。
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.transform.stream.StreamSource;

public class Main {

  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("input.xml");
    Home home = unmarshaller.unmarshal(xml, Home.class).getValue();

    for (Object object : home.any) {
      System.out.println(object.getClass());
    }
  }

  @XmlRootElement(name = "Animal")
  public static class Animal {

  }

  @XmlRootElement(name = "Person")
  public static class Person {
  }

  @XmlAccessorType(XmlAccessType.FIELD)
  public static class Home {
    @XmlAnyElement(lax = true)
    protected List<Object> any;
  }
}