Add XML comments into marshaled file(将 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 注释添加到编组文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 XML 注释添加到编组文件中


- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01