StAX end element tag with "<element attributes.. />" rather than whole end tag </element>

StackOverflow https://stackoverflow.com/questions/17489791

  •  02-06-2022
  •  | 
  •  

質問

I am streaming XML document, the following is the sample code.

final XMLOutputFactory xof =  XMLOutputFactory.newInstance();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
final XMLStreamWriter xtw = xof.createXMLStreamWriter(os);
xtw.writeStartDocument("utf-8", "1.0");
xtw.writeStartElement("Buddy");
xtw.writeAttribute("Name", "AB");
xtw.writeAttribute("Age", "25");
xtw.writeAttribute("petName", "XX");
xtw.writeEndElement();
xtw.close();

This produces

<?xml version="1.0" encoding="utf-8"?><Buddy Name="AB" Age="25" petName="XX"></Buddy>

How can I make StAX write

<?xml version="1.0" encoding="utf-8"?><Buddy Name="AB" Age="25" petName="XX"/>

i.e. the end tag "" is not required, it should end the tag as soon as the attributes are written. Any ideas?

INTENTION: To minimise the number of bytes sent over the network. Roughly 15k messages per second. Hence its worth saving some bytes per message.

役に立ちましたか?

解決

You should use writeEmptyElement(...) for this:

xtw.writeStartDocument("utf-8", "1.0");
xtw.writeEmptyElement("Buddy");
xtw.writeAttribute("Name", "AB");
xtw.writeAttribute("Age", "25");
xtw.writeAttribute("petName", "XX");
xtw.writeEndDocument();

No writeEndElement() is needed for empty elements.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top