Convert XML to Polymorphic Object using JAX-B

Here is an example of how you can convert XML to polymorphic objects using JAX-B.

Abstract Animal Class

package com.memorynotfound.xml.jaxb;

public abstract class Animal {

}

Cat Inherits from Animal

package com.memorynotfound.xml.jaxb;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "cat")
public class Cat extends Animal {

}

Dog Inherits from Animal

package com.memorynotfound.xml.jaxb;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "dog")
public class Dog extends Animal {

}

Root entity class for converting list of animals

package com.memorynotfound.xml.jaxb;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

@XmlRootElement(name = "root")
public class Root {

    private List<Animal> animals;

    public List<Animal> getAnimals() {
        return animals;
    }

    @XmlElementWrapper(name = "animals")
    @XmlElements({
            @XmlElement(name = "dog", type = Dog.class),
            @XmlElement(name = "cat", type = Cat.class)
    })
    public void setAnimals(List<Animal> animals) {
        this.animals = animals;
    }

    @Override
    public String toString() {
        return "Root{" +
                "animals=" + animals +
                '}';
    }
}

Convert XML to Polymorphic Object

package com.memorynotfound.xml.jaxb;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

public class ConvertXmlToObject {

    public static void main(String... args) throws JAXBException {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<root>\n" +
                "    <animals>" +
                "        <dog></dog>" +
                "        <cat></cat>" +
                "    </animals>\n" +
                "</root>";

        // create jaxb context
        JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        Root root = (Root)unmarshaller.unmarshal(new StringReader(xml));
        System.out.println(root);
    }
}

Output

Root{animals=[[email protected], [email protected]]}

You may also like...