Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 201
DMC19 Avatar asked Aug 16 '17 12:08

DMC19


People also ask

How does JAXB marshalling work?

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.

What is Jaxb_formatted_output?

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.


1 Answers

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")
like image 97
DMC19 Avatar answered Sep 17 '22 08:09

DMC19