Java HTML / XML How to - Create XML document with StAX








Question

We would like to know how to create XML document with StAX.

Answer

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
// w w w. j av a  2 s . co  m
public class Main {

  public static void main(String[] args) throws Exception {
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEventWriter writer = XMLOutputFactory.newInstance()
        .createXMLEventWriter(System.out);

    writer.add(eventFactory.createStartElement("ns1", "http://www.e.com/ns1",
        "sample", null, null));
    writer.add(eventFactory.createNamespace("ns1", "http://www.e.com/ns1"));
    writer.add(eventFactory.createNamespace("ns2", "http://www.e.com/ns2"));
    writer.add(eventFactory.createAttribute("ns2", "http://www.e.com/ns2",
        "attribute", "true"));
    writer.add(eventFactory.createEndDocument());
    writer.flush();
  }

}

The code above generates the following result.