Java Reference
In-Depth Information
get a reference to a parser and call its methods with objects representing the input files. The
difference is that the parser returns an XML DOM, a tree of objects in memory.
XParse
in
Example 20-8
simply parses an XML document. Despite the simplicity, I use it a lot;
whenever I have an XML file whose validity is in question, I just pass it to
XParse
.
Example 20-8. XParse.java
public
public static
static
void
void
main
(
String
[]
av
)
throws
throws
SAXException
{
iif
(
av
.
length
==
0
) {
System
.
err
.
println
(
"Usage: XParse file"
);
return
return
;
}
boolean
boolean
validate
=
false
false
;
Schema schema
=
null
null
;
try
try
{
for
for
(
int
int
i
=
0
;
i
<
av
.
length
;
i
++) {
iif
(
av
[
i
].
equals
(
"-v"
))
validate
=
true
true
;
else
else
if
(
av
[
i
].
equals
(
"-a"
)) {
// "create a SchemaFactory capable of understanding W3C schemas"
// -- from the Javadoc page
SchemaFactory schemaFactory
=
SchemaFactory
.
newInstance
(
XMLConstants
.
W3C_XML_SCHEMA_NS_URI
);
// load the W3c XML schema, represented by a Schema instance
String schemaLocation
=
av
[++
i
];
File schemaFile
=
new
new
File
(
schemaLocation
);
iif
(!
schemaFile
.
exists
()) {
throw
throw new
new
IOException
(
"Schema location = "
+
schemaLocation
+
" does not exist"
);
}
schema
=
schemaFactory
.
newSchema
(
schemaFile
);
}
else
else
{
File xmlFile
=
new
new
File
(
av
[
i
]);
System
.
err
.
println
(
"Parsing "
+
xmlFile
.
getAbsolutePath
() +
"..."
);
DocumentBuilderFactory dbFactory
=
DocumentBuilderFactory
.
newInstance
();
iif
(
validate
) {
iif
(
schema
!=
null
null
) {
dbFactory
.
setSchema
(
schema
);
}
else
else
{
dbFactory
.
setValidating
(
true
true
);