Java HTML / XML How to - Map two xmls with different rootelement name to the same java object








Question

We would like to know how to map two xmls with different rootelement name to the same java object.

Answer

import java.io.StringReader;
//w  w  w .ja v  a  2  s  .  co m
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

public class Main {
  public static void main(String[] args) throws Exception {
    String xml1 = "<abc><name>hello</name></abc>";
    String xml2 = "<xyz><name>hello</name></xyz>";
    Unmarshaller unmarshaller = JAXBContext.newInstance(Foo.class)
        .createUnmarshaller();
    Object o1 = unmarshaller.unmarshal(new StringReader(xml1));
    Object o2 = unmarshaller.unmarshal(new StringReader(xml2));
    System.out.println(o1);
    System.out.println(o2);
  }

  @XmlSeeAlso({ Foo.Foo_1.class, Foo.Foo_2.class })
  static class Foo {
    @XmlRootElement(name = "abc")
    static class Foo_1 extends Foo {
    }

    @XmlRootElement(name = "xyz")
    static class Foo_2 extends Foo {
    }

    @XmlElement
    String name;

    @Override
    public String toString() {
      return "Foo{name='" + name + '\'' + '}';
    }
  }
}