There are several obstacles that need to be overcome in your use case:
- Comments are not stored in byte code for the class, so you will need to make them available elsewhere.
- The JAXB API does not provide a way to map to node content.
The following is an approach that might work for you: StAX with JAXB and using Marshaller.Listener .
Java Model
Client
import javax.xml.bind.annotation.*; @XmlRootElement @XmlType(propOrder={"name", "address"}) @XmlAccessorType(XmlAccessType.FIELD) public class Customer { private String name; private Address address; public Customer() { } public Customer(String name, Address address) { this.name = name; this.address = address; } }
Address
import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class Address { String street; public Address() { } public Address(String street) { this.street = street; } }
Demo code
MyMarshalListener
import javax.xml.bind.Marshaller; import javax.xml.stream.*; public class MyMarshallerListener extends Marshaller.Listener { private XMLStreamWriter xsw; public MyMarshallerListener(XMLStreamWriter xsw) { this.xsw = xsw; } @Override public void beforeMarshal(Object source) { try { xsw.writeComment("Before: " + source.toString()); } catch(XMLStreamException e) {
Demo
import javax.xml.bind.*; import javax.xml.stream.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Customer.class); Address address = new Address("123 A Street"); Customer customer = new Customer("Jane", address); XMLOutputFactory xof = XMLOutputFactory.newFactory(); XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out); Marshaller marshaller = jc.createMarshaller(); marshaller.setListener(new MyMarshallerListener(xsw)); marshaller.marshal(customer, xsw); xsw.close();; } }
Real output
<?xml version="1.0" ?>
Formatted output
Here is the formatting result:
<?xml version="1.0" ?>
source share