App下載
首頁javastaxJava HTML/XML - 如何使用StAX創(chuàng)建XML文檔

Java HTML/XML - 如何使用StAX創(chuàng)建XML文檔

我們想知道如何使用StAX創(chuàng)建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();
  }

}