Friday, April 1, 2011

Skip XML declaration in JAXB

By default JAXB outputs XML declaration when you marshal your objects:
For example, this:

JAXBContext context = JAXBContext.newInstance(Command.class, Message.class...);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(command, writer);
will output this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<message channel="test"/>


If you don't need to use XML declaration in your JAXB output, it is easy to skip it by setting property "jaxb.fragment" to true. So, this:
JAXBContext context = JAXBContext.newInstance(Command.class, Message.class...);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty("jaxb.fragment", Boolean.TRUE);
marshaller.marshal(command, writer);
will output only this:
<message channel="test"/>


2 comments:

  1. For further readers.
    There is a field for "jaxb.fragment" in Marshaller.class.

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

    ReplyDelete
  2. Can you please share some more details like how to implement this full functionality.

    ReplyDelete