Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringReader;

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 + '\'' + '}';
        }
    }
}