【问题标题】:StAX end element tag with "<element attributes.. />" rather than whole end tag </element>StAX 结束元素标签,带有“<element attributes.. />”而不是整个结束标签 </element>
【发布时间】:2023-03-19 01:33:01
【问题描述】:

我是流XML文档,下面是示例代码。

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

这会产生

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

如何让 StAX 写入

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

即结束标记“”不是必需的,它应该在写入属性后立即结束标记。有什么想法吗?

意图:尽量减少通过网络发送的字节数。每秒大约 15k 条消息。因此,为每条消息节省一些字节是值得的。

【问题讨论】:

    标签: java stax


    【解决方案1】:

    您应该为此使用writeEmptyElement(...)

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

    空元素不需要writeEndElement()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 2019-12-10
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多