Search code examples
javaxmljaxb

JAXB multiple @XmlRootElement


I have a class annotated as follows:

@XmlRootElement(name="response")
@XmlType(propOrder={"paymentid", 
                    "result",
                    "responsecode", 
                    "authorizationcode", 
                    "merchantorderid", 
                    "rrn", 
                    "cardcountry", 
                    "cardtype"})
public class MOTOResponseIn {
...
}

The root element of the mapped XML could be also be error beside response.

How can I annotate the class so that both root elements are allowed?


Solution

  • In this case @XmlRootElement can not be used. You have to use ObjectFactory. The @XmlElementDecl annotation is used to represent root elements that correspond to named complex types. It is placed on a factory method in a class annotated with @XmlRegistry (when generated from an XML schema this class is always called ObjectFactory). The factory method returns the domain object wrapped in an instance of JAXBElement Hope this url will help.

    https://dzone.com/articles/jaxb-and-root-elements