JAXB write arbitrary text as first line of XML file generated from stream

koepke

New Member
I am using JAXB to marshal out objects and current my console output differs from my generated XML file: Console: \[code\]<!-- My awesome comment --> <?xml version="1.0" encoding="UTF-8" standalone="yes"?><Cat> <name>Toby</name></Cat>\[/code\]Generated: \[code\]<Cat> <name>Toby</name></Cat>\[/code\]I expect the output in the console to match what is generated within \[code\]Cat.xml\[/code\] however this is not the case. My question is what is incorrect in my approach to generate a "correct" \[code\]Cat.xml\[/code\]?Minimum functioning program below:\[code\]public class CatDriver{ public static void main(String[] args) throws JAXBException, IOException, ParserConfigurationException, TransformerException { Cat cat = new Cat(); cat.setName("Toby"); JAXBContext context = JAXBContext.newInstance(Cat.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.setProperty( "com.sun.xml.bind.xmlHeaders", "<!-- My awesome comment" + " --> \n <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"); m.marshal(cat, System.out); Writer w = null; try { w = new FileWriter("C:/test/Cat.xml"); m.marshal(cat, w); } finally { try { w.close(); } catch (Exception e) { } } }}\[/code\]\[code\]@XmlRootElement(name = "Cat")class Cat { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; }}\[/code\]
 
Back
Top