JAXB unmarshalling without XmlRootElement annotation?

If you cannot add XmlRootElement to existing bean you can also create a holder class and mark it with annotation as XmlRootElement. Example below:-

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class CustomerHolder 
{
    private Customer cusotmer;

    public Customer getCusotmer() {
        return cusotmer;
}

    public void setCusotmer(Customer cusotmer) {
        this.cusotmer = cusotmer;
    }
}

Following code is used to marshall and unmarshall withot @XmlRootElement

public static void main(String[] args) {

        try {

            StringWriter stringWriter = new StringWriter();

            Customer c = new Customer();
            c.setAge(1);
            c.setName("name");

            JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.marshal(new JAXBElement<Customer>( new QName("", "Customer"), Customer.class, null, c), stringWriter);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            InputStream is = new ByteArrayInputStream(stringWriter.toString().getBytes());
            JAXBElement<Customer> customer = (JAXBElement<Customer>) jaxbUnmarshaller.unmarshal(new StreamSource(is),Customer.class);

            c = customer.getValue();

          } catch (JAXBException e) {
            e.printStackTrace();
          }

}

Above code works only if you adding @XmlAccessorType(XmlAccessType.PROPERTY) on Customer class, or make private all attributes.

Tags:

Java

Jaxb