我想对通过JAXB生成的XML文件添加一些注释,但据我所知,这似乎不可能。我正在制作的文件偶尔会被人类手工修改,所以我希望能够提供一些注释以及文件中存在一些常用的XML标记,但注释掉了。
举个例子,我可以做这样的事情:
OPENEDX_RELEASE="open-release/eucalyptus.3"
答案 0 :(得分:1)
自定义XML Stream Writer可以做到这一点。
例如,以下XML Stream Writer将在特定标记结束后附加注释:(此示例使用DelegatingXMLStreamWriter,它允许链接不同的编写器:https://github.com/apache/cxf/blob/master/core/src/main/java/org/apache/cxf/staxutils/DelegatingXMLStreamWriter.java)
public class CommentingXMLStreamWriter extends DelegatingXMLStreamWriter
{
private final Deque<String> stack = new ArrayDeque<>();
private final Map<String, String> afterEndElementComments;
public CommentingXMLStreamWriter(
final XMLStreamWriter writer,
final Map<String, String> afterEndElementComments)
{
super(writer);
this.afterEndElementComments = afterEndElementComments;
}
@Override
public void writeStartElement(String localName) throws XMLStreamException
{
super.writeStartElement(localName);
stack.addFirst(localName);
}
@Override
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException
{
super.writeStartElement(namespaceURI, localName);
stack.addFirst(localName);
}
@Override
public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException
{
super.writeStartElement(prefix, localName, namespaceURI);
stack.addFirst(localName);
}
@Override
public void writeEndElement() throws XMLStreamException
{
super.writeEndElement();
final String localName = stack.pollFirst();
if (localName == null)
return;
final String comment = afterEndElementComments.get(localName);
if (comment == null)
return;
super.writeComment(comment);
}
}
通过将现有XML Stream Writer和映射从标记名称传递给注释来创建此类的实例。
代码可以很容易地扩展到在标记开始之前或在writeStartElement方法中通过执行注释输出之后输出注释。