import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; public class XMLGenerator { public static void main(String[] args) throws Exception { XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(System.out); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("book"); xmlStreamWriter.writeStartElement("title"); xmlStreamWriter.writeCharacters("Java Programming"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); // Ends the "book" element. xmlStreamWriter.writeEndDocument(); // Terminates the document. xmlStreamWriter.flush(); xmlStreamWriter.close(); } }
import java.io.FileOutputStream; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; public class XMLGenerator { public static void main(String[] args) throws Exception { XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); try (FileOutputStream fos = new FileOutputStream("books.xml")) { XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(fos); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("books"); // Add book elements and other elements. xmlStreamWriter.writeEndElement(); // Ends the "books" element. xmlStreamWriter.writeEndDocument(); // Terminates the document. xmlStreamWriter.flush(); } // The XMLStreamWriter is automatically closed here. } }Package Library: The javax.xml.stream package contains the XMLStreamWriter interface and related classes and interfaces for generating and reading XML documents using the StAX API.