0

I would like to add some comments to an XML file produced via JAXB, but as far as I can tell, this doesn't seem to be possible. The file that I'm producing is expected to be hand modified by humans occasionally, so I want to be able to provide some comments as well as have some commonly used XML tags present in the file, but commented out.

As an example, I would be able to do something like this:

...
<!--Uncomment the below lines in order to use capability FOOBAR--!>
<!--<FOOBAR someAttribute="someValue">
    <ChildElement1/>
    <ChildElement2/>
</FOOBAR>-->
...
NateW
  • 908
  • 1
  • 8
  • 28

1 Answers1

1

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.

denis
  • 417
  • 3
  • 8