8
votes

when I run 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..

1

1 Answers

12
votes

You can't marshal just a String as it doesn't have any root element information (hence the exception about the missing @XmlRootElement annotation), but you can wrap it in an instance of JAXBElement and then marshal that. JAXBElement is another way to supply this root element information to JAXB.

Example of Creating the JAXBElement

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

If you Generated your Model From an XML Schema

If you created your object model from an XML Schema. And you have a top-level XML element that is a data type like xs:string then there will be a convenience method on the generated ObjectFactory class that will help you create the JAXBElement instance.