简体   繁体   中英

Wrap a String of an instance of JAXBElement

I have the following code,

JAXBContext jc = JAXBContext.newInstance(TestResults.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
OutputStream os = new FileOutputStream( "nosferatu.xml" );
TestResults tr = new TestResults();
tr.setUuid(new JAXBElement<String>(new QName("uuid"),String.class, "uuidcontent"));
//ObjectFactory objectFactory = new ObjectFactory();
m.marshal(new JAXBElement<TestResults>(new QName("uri","local"),TestResults.class,new TestResults()), System.out);

in which I am trying to wrap the Java String Class as a jaxb element , since if I do not I get the

unable to marshal type “java.lang.String” error.

However when I try wrap the java.lang.string in a jaxb element , I get the following error

The method setUuid(String) in the type TestResults is not applicable for the arguments (JAXBElement<String>)

The setUuid method looks as follows

public void setUuid(java.lang.String value) {
    this.uuid = value;
}

How can I then wrap my String as a jaxb element where this error will not be thrown?

When marshalled as the root object an instance of String needs to be wrapped in a JAXBElement to provide the root element information (same as for any class without an @XmlRootElement annotation.

When marshalled as a field or property value the containing element is normally derived from the containing field/property so a JAXBElement by default is not required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM