Java Reference
In-Depth Information
catch (IOException ioe)
{
System.err.println("IOE: "+ioe);
}
catch (XMLStreamException xmlse)
{
System.err.println("XMLSE: "+xmlse);
}
}
}
Although
Listing 10-18
is fairly easy to follow, you might be somewhat confused
bytheduplicationofnamespaceURIsinthe
setPrefix()
and
writeStartEle-
ment()
methodcalls.Forexample,youmightbewonderingabouttheduplicateURIs
in
xmlsw.setPrefix("h", "http://www.w3.org/1999/xhtml");
and
its
xmlsw.writeStartElement("http://www.w3.org/1999/xhtml",
"html");
successor.
The
setPrefix()
methodcallcreatesamappingbetweenanamespaceprefix(the
value) and a URI (the key) without generating any output. The
writeStartEle-
ment()
methodcallspecifiestheURIkey,whichthismethodusestoaccesstheprefix
value,whichitthenprepends(withacoloncharacter)tothe
html
starttag'snamebe-
fore writing this tag to the underlying writer.
Creating Documents with Event-Based Writers
An event-based writer is created by calling one of
XMLOutputFactory
's
cre-
ateXMLEventWriter()
methods, such as
XMLEventWriter cre-
ateXMLEventWriter(Writer writer)
. These methods throw
XMLStreamException
when the event-based writer cannot be created.
The following example creates an event-based writer whose destination is a file
named
recipe.xml
:
Writer writer = new FileWriter("recipe.xml");
XMLEventWriter xmlew = xmlof.createXMLEventWriter(writer);
Thehigh-level
XMLEventWriter
interfacedeclaresthe
void add(XMLEvent
event)
methodforaddingeventsthatdescribeinfosetitemstotheoutputstreamim-
plemented by the underlying writer. Each argument passed to
event
is an instance