Problems with JAXB, Marshal - Failed to marshal the type "java.lang.String"

when I start the marshal operation, I get the following error:

javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an @XmlRootElement annotation] ... Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "java.lang.String" as an element because it is missing an @XmlRootElement annotation at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:237) at com.sun.xml.internal.bind.v2.runtime.LeafBeanInfoImpl.serializeRoot(LeafBeanInfoImpl.java:126) at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:483) at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308) ... 6 more 

This is my function for Marshalling ...

 public StringBuffer Marshaller(Object marshall){ // make marshalling->Java to XML StringWriter writer = new StringWriter(); try { JAXBContext jaxbContext=JAXBContext.newInstance(marshall.getClass()); Marshaller jaxbMarshaller=jaxbContext.createMarshaller(); // Γ§Δ±ktΔ± jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(marshall, writer); System.out.println(writer.getBuffer().toString()); } catch (PropertyException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } return writer.getBuffer(); } 

Thanks for your interests ..

+6
java xml jaxb
source share
1 answer

You cannot marshal only String , since it has no root element information (hence the exception to the missing @XmlRootElement annotation), but you can wrap it in a JAXBElement instance and then marshal that. JAXBElement is another way to pass this root element information to JAXB.

JAXBElement creation JAXBElement

 JAXBElement<String> jaxbElement = new JAXBElement(new QName("root-element"), String.class, string); 

If you created your model from an XML schema

If you created your object model from an XML schema. And you have a top-level XML element, which is a data type, for example xs:string , then a convenience method will be created for the generated ObjectFactory class, which will help you create an instance of JAXBElement .

+9
source share

All Articles