首页javastaxJava HTML/XML - 如何使用StAX创建XML文档

Java HTML/XML - 如何使用StAX创建XML文档

我们想知道如何使用StAX创建XML文档。
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;

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();
  }

}