Java Reference
In-Depth Information
}
catch (SAXException saxe)
{
// XML document is invalid!
}
This example refers to XSLT types such as
Source
. I explore XSLT later in this
chapter.
After the factory has been configured, call its
DocumentBuilder newDocu-
mentBuilder()
methodtoreturnadocumentbuilderthatsupportstheconfiguration,
as demonstrated here:
DocumentBuilder db = dbf.newDocumentBuilder();
If a document builder cannot be returned (perhaps the factory cannot create a docu-
mentbuilderthatsupportsXMLnamespaces),thismethodthrowsa
ParserConfig-
urationException
instance.
Assuming that you'vesuccessfully obtained adocument builder,what happens next
depends on whether you want to parse or create an XML document.
Parsing XML Documents
DocumentBuilder
provides several overloaded
parse()
methods for parsing an
XMLdocumentintoanodetree.Thesemethodsdifferinhowtheyobtainthedocument.
Forexample,
Document parse(String uri)
parsesthedocumentthat'sidenti-
fied by its string-based URI argument.
Note
Each
parse()
method throws
java.lang.IllegalArgumentException
when
null
ispassedasthemeth-
od's first argument,
IOException
when an input/output problem occurs, and
SAXException
when the document cannot be parsed. This last exception type im-
pliesthat
DocumentBuilder
's
parse()
methodsrelyonSAXtotakecareofthe
actualparsingwork.Becausetheyaremoreinvolvedinbuildingthenodetree,DOM
parsers are commonly referred to as
document builders
.
Thereturned
org.w3c.dom.Document
objectprovidesaccesstotheparseddoc-
umentthroughmethodssuchas
DocumentType getDoctype()
,whichmakesthe
documenttypedeclarationavailablethroughthe
org.w3c.dom.DocumentType
in-
terface. Conceptually,
Document
is the root of the document's node tree.