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

时间:2016-06-06 14:58:33

标签: java xml stax

如果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>

请注意,没有&lt; / carname&gt;

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

1 个答案:

答案 0 :(得分:2)

这可以通过XMLStreamWriter.writeEmptyElement

来实现

而不是

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

使用

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