Laird Nelson
Laird Nelson

Reputation: 16238

XMLEventWriter: how can I tell it to write empty elements?

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?

Upvotes: 10

Views: 8001

Answers (5)

John Bentley
John Bentley

Reputation: 1834

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"));

Upvotes: 3

StaxMan
StaxMan

Reputation: 116572

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.

Upvotes: 2

user1675631
user1675631

Reputation: 396

writer.writeEmptyElement("some_element");
writer.writeAttribute("some_attribute", "some_value");

Upvotes: 7

thequark
thequark

Reputation: 756

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

Upvotes: 4

Jim Garrison
Jim Garrison

Reputation: 86774

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.

Upvotes: 3

Related Questions