Search code examples
javaxmlstax

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


I need to create XML Document that end with slash if XML element is in one line (<test/> instead of <test></test>)

Here is the sample code to create XML Docs as follows

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

But i want the XML docs should be like this

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

Note that, there is no </carname>

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

Solution

  • This can be accomplished by using XMLStreamWriter.writeEmptyElement:

    Instead of

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

    use

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