Java XmlStreamWriter-class And Method Code Example


Here is an example of how to use the XmlStreamWriter class from the Apache Commons IO library in Java:

import org.apache.commons.io.output.XmlStreamWriter;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import java.io.ByteArrayOutputStream;

public class Example {
    public static void main(String[] args) throws XMLStreamException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XmlStreamWriter writer = new XmlStreamWriter(baos, "UTF-8");

        writer.writeStartDocument();
        writer.writeStartElement("root");
        writer.writeStartElement("element");
        writer.writeAttribute("attribute", "value");
        writer.writeCharacters("content");
        writer.writeEndElement();
        writer.writeEndElement();
        writer.writeEndDocument();

        writer.flush();
        writer.close();

        String xml = baos.toString("UTF-8");
        System.out.println(xml);
    }
}

This example creates an instance of XmlStreamWriter with a ByteArrayOutputStream and UTF-8 encoding. Then, it creates an XML document with a root element, an child element and attribute and text on it. Then it flushes and close the writer. Finally, it prints the XML document as string.

Please note that this class is not thread-safe and uses the StAX API for XML writing and you may use the XMLOutputFactory to get the XmlStreamWriter instance.