将XML注释添加到封送文件中 [英] Add XML comments into marshaled file

查看:211
本文介绍了将XML注释添加到封送文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将对象编组到XML文件中。如何在该XML文件中添加注释?

I'm marshaling objects into an XML file. How can I add comments into that XML file?

推荐答案

我没有看到单独使用JAXB的方法。但是,我认为您可以利用DOM来获得所需的效果:

I do not see a way to do it with JAXB alone. However, I think you can leverage DOM to get the desired effect:

final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.getDOMImplementation().createDocument(null, null, null);

final Binder<Node> 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。

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.

这篇关于将XML注释添加到封送文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆