XMLEventWriter: how can I tell it to write empty elements?
Question
I do not see an option within javax.xml.stream.XMLEventWriter
or javax.xml.stream.XMLOutputFactory
to set either up in a way so that empty elements are written (instead of explicit start and end element pairs).
I see that Woodstox has a property to do this, but it is not standardized.
Am I missing any obvious way to do this?
Solution
No. There is no semantic difference between <x/>
and <x></x>
and the standard APIs do not provide a way to request one or the other.
OTHER TIPS
writer.writeEmptyElement("some_element");
writer.writeAttribute("some_attribute", "some_value");
Setting property so that empty tags are generated like <x/>
works with WoodStox APIs:
WstxOutputFactory factory = new WstxOutputFactory();
factory.setProperty(WstxOutputFactory.P_AUTOMATIC_EMPTY_ELEMENTS, true);
I wanted indentation in XML tags. the setIndentation method is working with neither javax.xml.stream.XMLOutputFactory nor org.codehaus.stax2.XMLOutputFactory2
In several of the answers and comments there is some confusion.
StAX has two APIs:
- The "Cursor API" using
XMLStreamReader
andXMLStreamWriter
; and - The "Iterator API" using
XMLEventReader
andXMLEventWriter
;
Outputting an empty element with a single tag, <example/>
, is possible with the Cursor API usingXMLStreamWriter
:
xmlStreamWriter.writeEmptyElement("example");
Outputting an empty element with a single tag, <example/>
, is not possible with the Iterator API using XMLEventWriter
, as far as I know. In this case you're stuck with producing an empty element with two tags <example></example>
:
xmlEventWriter.add(xmlEventFactory.createStartElement("", null, "example"));
xmlEventWriter.add(xmlEventFactory.createEndElement("", null, "example"));
You probably know this already, but XMLStreamWriter does have method for specifying that it should be "real" empty element. XMLEventWriter is missing a few pieces that lower level interface has.