I'm trying to marshal a java object but I want to remove the header that Jaxb is introducing.
Object:
@XmlRootElement
public class FormElement implements Serializable {
private String id;
private String name;
private Integer order;
}
Expected output:
<element>
<id>asd</id>
<name>asd</name>
<order>1</order>
</element>
My output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<formElement>
<id>asd</id>
<name>asd</name>
<order>1</order>
</formElement>
My marshal method:
public String marshal() {
JAXBContext context;
try {
context = JAXBContext.newInstance(FormElement.class);
Marshaller marshaller = context.createMarshaller();
StringWriter stringWriter = new StringWriter();
marshaller.marshal(this, stringWriter);
return stringWriter.toString();
} catch (JAXBException e) {
}
return null;
}
How can I remove it?
Thanks in advance.
In JAXB, marshalling involves parsing an XML content object tree and writing out an XML document that is an accurate representation of the original XML document, and is valid with respect the source schema. JAXB can marshal XML data to XML documents, SAX content handlers, and DOM nodes.
JAXB_FORMATTED_OUTPUT. The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation. static String.
I have solved it using
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
and adding (name = "element")
to the @XmlRootElement
annotation.
The correct method:
public String marshal() {
JAXBContext context;
try {
context = JAXBContext.newInstance(FormElement.class);
Marshaller marshaller = context.createMarshaller();
StringWriter stringWriter = new StringWriter();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.marshal(this, stringWriter);
return stringWriter.toString();
} catch (JAXBException e) {
String mess = "Error marshalling FormElement " + e.getMessage()
+ (e.getCause() != null ? ". " + e.getCause() : " ");
System.out.println(mess);
}
return null;
}
And the correct annotation:
@XmlRootElement(name = "element")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With