I have an understanding problem of how the following code works:
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLOutputFactory xof = XMLOutputFactory.newFactory();
XMLEventReader reader = xif.createXMLEventReader(/* ... */);
XMLEventWriter writer = xof.createXMLEventWriter(/* ... */);
writer.add(reader);
The method writer.add([some reader]) reads all events from reader and writes them consequently. Sadly, following happens:
The input
<root><c/></root>
gets transformed to
<root><c><c/></root>
I know, from XML point of view, these are equal trees, but not for a human 😉
What can I do to get the same output?
FYI: I need a XMLEvent[Reader|Writer] pair later to filter “XML events”.
According to the list of XMLEvents it seems like there is no way to make the distinction and it will indeed generate a
StartElementandEndElementevent. The consumer would need to optimize for the case when aStartElementis immediately followed by anEndElement.This is apparently not the case of the
XMLEventReaderreturned by the factory. If you want to optimize this behavior yourself, I see no other way than to do something likeXMLEventReaderimplementation returned bycreateXMLEventReaderXMLEventReaderimplementation to optimize this caseXMLInputFactoryand overridecreateXMLEventReaderto return an instance of yourXMLEventReadersubclassIf this sounds too complicated (or doesn’t work), I would suggest that you go with a solution that uses
XMLStreamWriter. This one has a dedicated methodwriteEmptyElement.(Or you can give a try to my home-made pretty printer, it’s based on
XMLStreamWriter)