DMC19
DMC19

Reputation: 927

JAXB - How to marshal java object without header

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.

Upvotes: 9

Views: 15190

Answers (1)

DMC19
DMC19

Reputation: 927

I have solved it using

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

and adding (name = "element") to the @XmlRootElement annotation.

The right 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 right annotation:

@XmlRootElement(name = "element")

Upvotes: 29

Related Questions