Is there any way we can un-marshall for a class without @XmlRootElement annotation? Or are we obligated to enter the annotation?
for example:
public
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.
I use the generic solution as follows:
public static <T> String objectToXmlStringNoRoot(T obj, Class<T> objClass, final String localPart) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(objClass);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// To format XML
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//If we DO NOT have JAXB annotated class
JAXBElement<T> jaxbElement = new JAXBElement<>(new QName("", localPart), objClass, obj);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(jaxbElement, sw);
return sw.toString();
}
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;
}
}