http://tutorials.jenkov.com/java-xml/stax-xmleventwriter.html에서 가져옴


The XMLEventWriter class in the Java StAX API allows you to write StAX XMLEvent's either to aWriter, an OutputStream, or a Result (special JAXP object).

Here is a simple example that writes a series of events to disk, using a FileWriter:

XMLOutputFactory factory      = XMLOutputFactory.newInstance();
XMLEventFactory  eventFactory = XMLEventFactory.newInstance();

try {
    XMLEventWriter writer =
            factory.createXMLEventWriter(
                    new FileWriter("data\\output.xml"));

    XMLEvent event = eventFactory.createStartDocument();
    writer.add(event);

    event = eventFactory.createStartElement(
            "jenkov", "http://jenkov.com", "document");
    writer.add(event);

    event = eventFactory.createNamespace(
            "jenkov", "http://jenkov.com");
    writer.add(event);

    event = eventFactory.createAttribute
            ("attribute", "value");
    writer.add(event);

    event = eventFactory.createEndElement(
            "jenkov", "http://jenkov.com", "document");
    writer.add(event);

    writer.flush();
    writer.close();
} catch (XMLStreamException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

The result of executing this code is the following XML file (line breaks inserted for readability):

<?xml version='1.0' encoding='UTF-8'?>
<jenkov:document xmlns:jenkov="http://jenkov.com" attribute="value">
</jenkov:document>

As you can see, it is possible to generate XML using XMLEvent's and the XMLEventWriter. But, if you are looking to just output some quick XML, you might be better off using the XMLStreamWriterinstead. It's API is easier to work with, and results in more dense code.


Chaining XMLEventReader and XMLEventWriter

It is possible to add the XMLEvent's available from an XMLEventReader directly to an XMLEventWriter. In other words, you are pooring the XML events from the reader directly into the writer. You do so using the XMLEventWriter.add(XMLEventReader) method.

+ Recent posts