import javax.xml.stream.*; import java.io.*; public class XMLWriter { public static void main(String[] args) { try { XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter("output.xml")); writer.writeStartElement("root"); writer.writeStartElement("element"); writer.writeCharacters("Hello, world!"); writer.writeEndElement(); writer.writeEndElement(); writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
import javax.xml.stream.*; import java.io.*; public class XMLWriter { public static void main(String[] args) { try { XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = factory.createXMLStreamWriter(System.out); writer.writeStartElement("root"); writer.writeStartElement("element"); writer.writeCharacters("Hello, world!"); writer.writeEndElement(); writer.writeEndElement(); writer.flush(); } catch (Exception e) { e.printStackTrace(); } } }In this example, we create an XMLStreamWriter that writes to standard output. The flush() method is called to ensure that all data is written to the console. The javax.xml.stream package provides the StAX API, which is part of the Java API for XML Processing (JAXP).