Using the Streaming API for XML StAX 4-15
7.
Close the output stream. See Section 4.3.6, Closing the Output Stream.
4.3.1 Example of Generating XML Using StAX
The following example shows a simple program that uses the XMLStreamWriter interface of StAX to generate an XML document.
The program first creates an instance of an XMLStreamWriter, specifying that the output be written to the file outFile.xml in the current directory. Then, using
various writeXXX methods, it builds an XML file that looks like the following:
?xml version=1.0 encoding=utf-8? --this is a comment--
person xmlns:one=http:namespaceOne gender=f one:name hair=pigtails freckles=yesPippi Longstockingone:name
person
The XMLStreamWriter interface does not check for that an XML document is well-formed; it is the programmers responsibility to ensure that, for example, each
start element has a corresponding end element, and so on. The example also shows how to use the writeCharacters\n method to add new lines to the output to
make the XML more readable when writing to a text file.
The code in bold is described in later sections. package examples.basic;
import java.io.FileOutputStream; import java.util.Iterator;
import javax.xml.stream.;
import javax.xml.namespace.QName; This is a simple example that illustrates how to use the
the XMLStreamWriter class to generate XML. The generated XML file looks like this:
?xml version=1.0 encoding=utf-8? --this is a comment--
person xmlns:one=http:namespaceOne gender=f one:name hair=pigtails freckles=yesPippi Longstockingone:name
person author Copyright c 2003 by BEA Systems. All Rights Reserved.
public class Generate { public static void mainString args[] throws Exception {
Get an output factory XMLOutputFactory xmlof = XMLOutputFactory.newInstance;
System.out.printlnFACTORY: + xmlof;
4-16 Programming XML for Oracle WebLogic Server
Instantiate a writer XMLStreamWriter xmlw = xmlof.createXMLStreamWriternew FileOutputStream
outFile.xml;
System.out.printlnREADER: + xmlw + \n; Generate the XML
Write the default XML declaration xmlw.writeStartDocument;
xmlw.writeCharacters\n; xmlw.writeCharacters\n;
Write a comment xmlw.writeCommentthis is a comment;
xmlw.writeCharacters\n;
Write the root element person with a single attribute gender xmlw.writeStartElementperson;
xmlw.writeNamespaceone, http:namespaceOne; xmlw.writeAttributegender,f;
xmlw.writeCharacters\n;
Write the name element with some content and two attributes xmlw.writeCharacters ;
xmlw.writeStartElementone, name, http:namespaceOne; xmlw.writeAttributehair,pigtails;
xmlw.writeAttributefreckles,yes; xmlw.writeCharactersPippi Longstocking;
End the name element xmlw.writeEndElement;
xmlw.writeCharacters\n;
End the person element xmlw.writeEndElement;
End the XML document xmlw.writeEndDocument;
Close the XMLStreamWriter to free up resources xmlw.close;
} }
4.3.2 Getting the XMLStreamWriter Object