创建以斜杠结尾的 XML 文档('<test />' 而不是 '<test></test>')

Create XML Document that end with slash ('<test />' instead of '<test></test>')

如果 XML 元素在一行中(<test/> 而不是 <test></test>),我需要创建以斜杠结尾的 XML 文档

下面是创建XML文档的示例代码

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars><supercars company="Ferrari">
<carname type="formula one"></carname>
<carname type="sports"></carname>
</supercars></cars>

但我希望 XML 文档应该像这样

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<cars><supercars company="Ferrari">
<carname type="formula one"/>
<carname type="sports"/>
</supercars></cars>

请注意,没有

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public class StAXCreateXMLDemo {
  public static void main(String[] args) {
  try {
     StringWriter stringWriter = new StringWriter();

     XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newInstance();    
     XMLStreamWriter xMLStreamWriter =  xMLOutputFactory.createXMLStreamWriter(stringWriter);

     xMLStreamWriter.writeStartDocument();
     xMLStreamWriter.writeStartElement("cars");

     xMLStreamWriter.writeStartElement("supercars");            
     xMLStreamWriter.writeAttribute("company", "Ferrari");

     xMLStreamWriter.writeStartElement("carname");          
     xMLStreamWriter.writeAttribute("type", "formula one");

     xMLStreamWriter.writeEndElement();

     xMLStreamWriter.writeStartElement("carname");          
     xMLStreamWriter.writeAttribute("type", "sports");

     xMLStreamWriter.writeEndElement();

     xMLStreamWriter.writeEndElement();
     xMLStreamWriter.writeEndDocument();

     xMLStreamWriter.flush();
     xMLStreamWriter.close();

     String xmlString = stringWriter.getBuffer().toString();

     stringWriter.close();

     System.out.println(xmlString);

  } catch (XMLStreamException e) {
     e.printStackTrace();
  } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
  }
  }
  }

这可以通过使用 XMLStreamWriter.writeEmptyElement:

来完成

而不是

 xMLStreamWriter.writeStartElement("carname");
 xMLStreamWriter.writeAttribute("type", "formula one");
 xMLStreamWriter.writeEndElement();

使用

xMLStreamWriter.writeEmptyElement("carname");
xMLStreamWriter.writeAttribute("type", "formula one");