Java Reference
In-Depth Information
The
errorListener
object that is the argument must be of a class type that implements the
Er-
rorListener
interface.
ErrorListener
declares three methods, all with a
void
return type, and all can throw a
Transformer-
Exception
:
•
error(TransformerException te)
is called when a recoverable error occurs. The transformer
continues to process the document after this error. You can implement the method to throw a
TransformerException
if you want to terminate processing of the document.
•
fatalError(TransformerException te)
is called when a non-recoverable error occurs. Pro-
cessing the document may continue after this error but usually it won't. Your implementation of
this method should handle the error or throw a
TransformerException
if that is not possible, or
if you want to terminate document processing.
•
void warning(TransformerException te)
is called to report conditions that are not errors or
fatal errors. After this method returns, processing always continues. You can terminate processing
of the document by throwing a
TransformerException
from this method.
You are not obliged to implement an
ErrorListener
for a transformer to receive notification of errors. If
you don't, the default behavior is to report all errors to
System.err
and not to throw any exceptions. In gen-
eral you should implement an
ErrorListener
for a transformer to deal with errors appropriately. Throwing
a
TransformerException
from within the error handler is optional, but if the method does throw an excep-
tion, the implementation must declare that it does.
CREATING DOCUMENT OBJECTS
The simplest way to create a
Document
object programmatically is to call the
newDocument()
method for a
DocumentBuilder
object, and it returns a reference to a new empty
Document
object:
Document newDoc = builder.newDocument();
This is rather limited, especially because there's no way to modify the
DocumentType
node to reflect a
suitable
DOCTYPE
declaration because the
DocumentType
interface does not declare any.
There's an alternative approach that provides a bit more flexibility, but it is not quite so direct. You first
call the
getDOMImplementation()
method for the
DocumentBuilder
object:
DOMImplementation domImpl = builder.getDOMImplementation();
This returns an
org.w3c.dom
.
DOMImplementation
reference to an object that encapsulates the underly-
ing DOM implementation.
There are three methods you can call for a
DOMImplementation
object:
•
Document createDocument( String namespaceURI, String qualifiedName, Docu-
mentType doctype)
: Creates a
Document
object with the root element having the name
qual-
ifiedName
in the namespace specified by
namespaceURI
. The third argument specifies the
DOCTYPE
node to be added to the document. If you don't want to declare a
DOCTYPE
then
doctype
can be
null
. The method throws a
DOMException
if the second argument is incorrect in some
way.