Java HTML / XML How to - Use JAXB to Unmarshal @XmlAnyElement








Question

We would like to know how to use JAXB to Unmarshal @XmlAnyElement.

Answer

import java.util.List;
//  w  w w . j  a v  a 2  s . c  om
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;
  }
}

input.xml

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