XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(os); writer.writeStartDocument(); writer.writeStartElement("book"); writer.writeAttribute("id", "1"); writer.writeStartElement("title"); writer.writeCharacters("Java Programming"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.close();
XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(os); try { writer.writeStartDocument(); writer.writeStartElement("book"); writer.writeAttribute("id", "1"); writer.writeStartElement("title"); writer.writeCharacters("Java Programming"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); } finally { if (writer != null) { writer.close(); } }In this example, we use a try-finally block to ensure that the "close" method is called even if an exception is thrown during the writing process. The javax.xml.stream package provides a standard way to write XML documents in Java.