Java – How to instantiate an empty element with JAXB


I use JAXB to create XML messages. The XML I need to create is (for the sake of simplicity):


My code looks like this:

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "request")
public class Request {

    private String header;

    public String getHeader() {
      return header;

    public void setHeader(String header) {

The problem: the header element is not displayed (header is null). When header is set to an empty string, the following is displayed:


When I use as type Object instead of String, the result is even worse:

  <header xsi:type="xs:string" 

BTW: I'm using this code to create the XML string.

Is it possible to get an empty tag?

Best Answer

In XML, <header/> and <header></header> are the same thing. If you really want the former, then use a prettifier. javax.xml.transform.TransformerFactory.newTransformer() will probably do that for you.