Java Reference
In-Depth Information
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 a reference of type
DOMImplementation
to an object that encapsulates the underlying
DOM implementation. This interface type is defined in the
org.w3c.dom
package.
There are three methods you can call for a
DOMImplementation
object:
createDocument(
Creates a
Document
object with the root element having
the name
qualifiedName
that is defined 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 specified as
null
.
String namespaceURI,
String qualifiedName,
DocumentType doctype)
This method will throw an exception of type
DOMException
if the second argument is incorrect in some
way.
createDocumentType(
Creates a node of type
DocumentType
that represents a
DOCTYPE
declaration. The first argument is the qualified
name of the root element, the second argument is the public
ID of the external subset of the DTD, and the third
argument is its system ID. This method will also throw an
exception of type
DOMException
if the first argument
contains an illegal character or is not of the correct form.
String qualifiedName,
String publicID,
String systemID)
hasFeature(String feature,
String version)
Returns
true
if the DOM implementation has the feature
with the name
feature
. The second argument specifies the
DOM version number of the feature and can be either
"1.0"
or
"2.0"
with DOM level 2.
You can see from the first two methods here that there is a big advantage to using a
DOMImplementation
object to create a document. First of all, you can create a
DocumentType
object by calling the
createDocumentType()
method:
DocumentType doctype = null;
try {
doctype = domImpl.createDocumentType("sketch", null, "sketcher.dtd");
} catch(DOMException e) {
// Handle the exception
}
This code fragment creates a
DocumentType
node for an external
DOCTYPE
declaration with the name
sketch
, with the system ID
sketcher.dtd
. There is no public ID in this case since we specified the
second argument as
null
. You can now use the
DocumentType
object in the creation of a document: