background image

Creating a Stream Writer

<< Returning the Output | Building and Running the Writer Example >>
<< Returning the Output | Building and Running the Writer Example >>

Creating a Stream Writer

Creating a Stream Writer
The next step is to create an instance of XMLStreamWriter:
XMLStreamWriter xtw = null;
Writing the Stream
The final step is to write the XML stream. Note that the stream is flushed and closed after the
final EndDocument is written:
xtw = xof.createXMLStreamWriter(new FileWriter(fileName));
xtw.writeComment(
"all elements here are explicitly in the HTML namespace");
xtw.writeStartDocument(
"utf-8","1.0");
xtw.setPrefix(
"html", "http://www.w3.org/TR/REC-html40");
xtw.writeStartElement(
"http://www.w3.org/TR/REC-html40","html");
xtw.writeNamespace(
"html", "http://www.w3.org/TR/REC-html40");
xtw.writeStartElement(
"http://www.w3.org/TR/REC-html40","head");
xtw.writeStartElement(
"http://www.w3.org/TR/REC-html40","title");
xtw.writeCharacters(
"Frobnostication");
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeStartElement(
"http://www.w3.org/TR/REC-html40","body");
xtw.writeStartElement(
"http://www.w3.org/TR/REC-html40","p");
xtw.writeCharacters(
"Moved to");
xtw.writeStartElement(
"http://www.w3.org/TR/REC-html40","a");
xtw.writeAttribute(
"href","http://frob.com");
xtw.writeCharacters(
"here");
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeEndElement();
xtw.writeEndDocument();
xtw.flush();
xtw.close();
Returning the Output
When you run the Writer example, the CursorWriter class is compiled, and the XML stream is
parsed as events and written to a file named dist/CursorWriter-Output:
<!--all elements here are explicitly in the HTML namespace-->
<?xml version=
"1.0" encoding="utf-8"?>
<html:html xmlns:html=
"http://www.w3.org/TR/REC-html40">
<html:head>
<html:title>Frobnostication</html:title></html:head>
<html:body>
<html:p>Moved to <html:a href=
"http://frob.com">here</html:a>
Example Code
Chapter 18 · Streaming API for XML
581