import javax.xml.stream.*; public class Example1 { public static void main(String[] args) throws Exception { XMLOutputFactory factory = XMLOutputFactory.newFactory(); XMLStreamWriter writer = factory.createXMLStreamWriter(System.out); writer.writeStartDocument(); writer.writeStartElement("root"); writer.writeStartElement("element"); writer.writeCharacters("Hello, world!"); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } }
import javax.xml.bind.*; import javax.xml.stream.*; public class Example2 { public static void main(String[] args) throws Exception { JAXBContext context = JAXBContext.newInstance(Person.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Person person = new Person("John", "Doe"); XMLOutputFactory factory = XMLOutputFactory.newFactory(); XMLStreamWriter writer = factory.createXMLStreamWriter(System.out); marshaller.marshal(person, writer); writer.flush(); writer.close(); } } @XmlRootElement class Person { private String firstName; private String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }This code uses XMLStreamWriter together with the JAXB API to write an XML document from a Java object. It creates a JAXBContext for the Person class, and then creates a Marshaller to convert the object to XML. The XMLStreamWriter is created as before, and the Marshaller's marshal method is used to write the XML to the writer. In both examples, the javax.xml.stream package is used for XML processing, specifically the XMLStreamWriter class for writing XML documents.