A custom XML Stream Writer can do that.
For example the following XML Stream Writer will append comment after the end of specific tags: (this example makes use of DelegatingXMLStreamWriter which allows chaining different writers: 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);
}
}
Create the instance of this class by passing an existing XML Stream Writer and a map from tag names to comments.
The code can be easily extended to output comments before the start of a tag or after the by doing comment output in writeStartElement methods.