Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add XML comments into marshaled file

Tags:

java

xml

jaxb

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

like image 749
Oleksandr Avatar asked Aug 28 '09 14:08

Oleksandr


1 Answers

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);
like image 190
DanEEStar Avatar answered Oct 16 '22 10:10

DanEEStar