You can use JAXB and StAX and do the following:
Demo
If you want comments at the beginning of the document, you can write down their goals before using JAXB to marshal objects. You need to set the Marshaller.JAXB_FRAGMENT property to true so that JAXB does not write the XML declaration.
import javax.xml.bind.*; import javax.xml.stream.*; public class Demo { public static void main(String[] args) throws Exception { XMLOutputFactory xof = XMLOutputFactory.newFactory(); XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out); xsw.writeStartDocument(); xsw.writeComment("Author date"); JAXBContext jc = JAXBContext.newInstance(Foo.class); Foo foo = new Foo(); foo.setBar("Hello World"); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.marshal(foo, xsw); xsw.close(); } }
Domain Model (Foo)
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Foo { private String bar; public String getBar() { return bar; } public void setBar(String bar) { this.bar = bar; } }
Exit
<?xml version="1.0" ?><foo><bar>Hello World</bar></foo>
UPDATE
Using the StAX approach, the output will not be formatted. If you want to format, then it might be better for you:
import java.io.OutputStreamWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; public class Demo { public static void main(String[] args) throws Exception { OutputStreamWriter writer = new OutputStreamWriter(System.out, "UTF-8"); writer.write("<?xml version=\"1.0\" ?>\n"); writer.write("<!--Author date-->\n"); JAXBContext jc = JAXBContext.newInstance(Foo.class); Foo foo = new Foo(); foo.setBar("Hello World"); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.marshal(foo, writer); writer.close(); } }
source share