I'm marshaling objects into an XML file. How can I add comments into that XML file?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- Illegal to have multiple roots (start tag in epilo
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
If anyone comes to this now, like I just did, it is worth pointing out that the property to do this is now
com.sun.xml.bind.xmlHeaders
(no longer internal it seems), so you can solve the problem like this (I have only tried it with EclipseLink MOXY):The following information originally comes from Marshaller Properties in the JAXB RI Extensions documentation on jaxb.java.net:
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:
You can use this Java-Code:
I do not see a way to do it with JAXB alone. However, I think you can leverage DOM to get the desired effect:
Where jaxbContext is the JAXBContext object you are working with and jaxbObject is the object to be marshalled. This sample just appends the comment to the end of the document. For a different location, you would have to traverse the DOM through the doc object or use XPath to find the exact element you want the comment added to and use appendChild on it.