Java – Add XML comments into marshaled file

javajaxbxml

I'm marshaling objects into an XML file. How can I add comments into that XML file?

Best Solution

You can add comments right after the preamble with the proprietary Marshaller property com.sun.xml.bind.xmlHeaders (see XML Preamble Control)

In the included JAXB-implementation jdk1.6.0_29 the property is called "com.sun.xml.internal.bind.xmlHeaders"

See also question: How to add DOCTYPE and xml processing instructions when marshalling with JAXB?

So to get this XML with the test-comment after the preamble:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- Test Comment -->
<player>
    <name>Daniel</name>
    <birthday>1982-06-09T00:00:00+02:00</birthday>
</player>

You can use this Java-Code:

JAXBContext context = JAXBContext.newInstance(Player.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.setProperty("com.sun.xml.internal.bind.xmlHeaders", "\n<!-- Test Comment -->");
m.marshal(player, System.out);