Java Reference
In-Depth Information
Note
Youcanalsocallthe
XMLOutputFactory newInstance()
classmeth-
od but might not wish to do so because its same-named but parameterized compan-
ion method has been deprecated to maintain API consistency, and it is probable that
newInstance()
will be deprecated as well.
The
newFactory()
methods follow an ordered lookup procedure to locate the
XMLOutputFactory
implementation class. This procedure first examines the
javax.xml.stream.XMLOutputFactory
system property, and lastly chooses
thenameoftheJavaplatform'sdefault
XMLOutputFactory
implementationclass.If
thisprocedurecannotfindaclassname,oriftheclasscannotbeloaded(orinstantiated),
the method throws an instance of the
FactoryConfigurationError
class.
After creating the factory, call
XMLOutputFactory
's
void setProp-
erty(String name, Object value)
methodtosetvariousfeaturesandprop-
erties as necessary. The only property currently supported by all writers is
XMLOut-
putFactory.IS_REPAIRING_NAMESPACES
.Whenenabled(bypassing
true
or
a
Boolean
object, such as
Boolean.TRUE
, to
value
), the document writer takes
care of all namespace bindings and declarations, with minimal help from the applica-
tion.Theoutputisalwayswellformedwithrespecttonamespaces.Howeverenabling
this property adds some overhead to the job of writing the XML.
Creating Documents with Stream-Based Writers
A stream-based writer is created by calling one of
XMLOutputFactory
's
cre-
ateXMLStreamWriter()
methods, such as
XMLStreamWriter cre-
ateXMLStreamWriter(Writer writer)
. These methods throw
XMLStreamException
when the stream-based writer cannot be created.
The following example creates a stream-based writer whose destination is a file
named
recipe.xml
:
Writer writer = new FileWriter("recipe.xml");
XMLStreamWriter
xmlsw
=
xm-
lof.createXMLStreamWriter(writer);
The low-level
XMLStreamWriter
interface declares several methods for writing
infoset items to the destination. The following list describes a few of these methods:
•
void close()
closes this stream-based writer and frees any associated re-
sources. The underlying writer is not closed.
•
void flush()
writes any cached data to the underlying writer.