Java XMLStreamWriter write xml file

Description

Java XMLStreamWriter write xml file

import java.io.FileOutputStream;

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

public class Main {

   public static void main(String[] args) throws Exception {
      XMLOutputFactory factory = XMLOutputFactory.newFactory();
      try (FileOutputStream fos = new FileOutputStream("outputFile.xml")) {
         XMLStreamWriter writer = factory.createXMLStreamWriter(fos, "UTF-8");
         writer.writeStartDocument();/*  w w w.  j  a  v  a 2  s.c o  m*/
         writer.writeCharacters("\n");
         writer.writeStartElement("langs");
         writer.writeCharacters("\n");
         for (int i = 0; i < 3; i++) {
            writer.writeCharacters("\t");
            writer.writeStartElement("lang");
            writer.writeAttribute("id", String.valueOf(i));
            writer.writeCharacters("\n\t\t");
            writer.writeStartElement("name");
            writer.writeCharacters("tester");
            writer.writeEndElement();
            writer.writeCharacters("\n\t\t");
            writer.writeStartElement("feature");
            writer.writeCharacters("data");
            writer.writeEndElement();
            writer.writeCharacters("\n\t");
            writer.writeEndElement();
            writer.writeCharacters("\n");
         }
         writer.writeEndElement();
         writer.writeEndDocument();
         writer.close();
      }
   }
}



PreviousNext

Related