我没有看到有一种方法可以单独使用JAXB.但是,我认为您可以利用DOM来获得所需的效果:
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.getDOMImplementation().createDocument(null, null, null);
final Binder binder = jaxbContext.createBinder();
binder.marshal(jaxbObject, doc);
final Comment comment = doc.createComment("This is a comment");
doc.appendChild(comment);
final DOMSource domSource = new DOMSource(doc);
// use System.out for testing
final StreamResult streamResult = new StreamResult(System.out);
final TransformerFactory tf = TransformerFactory.newInstance();
final Transformer serializer = tf.newTransformer();
serializer.transform(domSource, streamResult);
其中jaxbContext是您正在使用的JAXBContext对象,jaxbObject是要编组的对象.此示例仅将注释添加到文档的末尾.对于不同的位置,您必须通过doc对象遍历DOM,或使用XPath查找要添加的注释的确切元素,并在其上使用appendChild.