10

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?

StaxMan
  • 113,358
  • 34
  • 211
  • 239
Laird Nelson
  • 15,321
  • 19
  • 73
  • 127

5 Answers5

7
writer.writeEmptyElement("some_element");
writer.writeAttribute("some_attribute", "some_value");
user1675631
  • 376
  • 3
  • 3
4

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

thequark
  • 726
  • 1
  • 7
  • 17
3

In several of the answers and comments there is some confusion.

StAX has two APIs:

  • The "Cursor API" using XMLStreamReader and XMLStreamWriter; 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"));
John Bentley
  • 1,676
  • 1
  • 16
  • 18
3

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.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • An implementation detail of the StAX writer included with the JDK by default: calling `writeStartElement("localname");writeEndElement()` results in a self-closing tag, while calling `writeStartElement("localname");writeCharacters(null);writeEndElement()` results in an opening tag immediately followed by a closing tag. – Barend Sep 09 '11 at 09:59
  • As you note, that is an implementation detail. Other serializers and later versions of StAX may or may not do this. – Jim Garrison Mar 24 '12 at 20:32
  • I just have an issue where JAXB chokes on `` but is fine with ``. So there seems to be a semantic difference? Or is it a bug in JAXB? – Puce Mar 24 '14 at 17:02
2

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.

ziesemer
  • 27,712
  • 8
  • 86
  • 94
StaxMan
  • 113,358
  • 34
  • 211
  • 239