Java Reference
In-Depth Information
briefly described in
Action Handling: Making Buttons Work
.
The most commonly used
methods are
startElement()
,
endElement()
, and
characters()
. The first two, obviously,
are called at the start and end of an element, and
characters()
is called when there is char-
acter data. The characters are stored in a large array, and you are passed the base of the array
and the offset and length of the characters that make up your text. Conveniently, there is a
string constructor that takes exactly these arguments. Hmmm, I wonder if they thought of
that . . .
To demonstrate this, I wrote a simple program using SAX to extract names and email ad-
dresses from an XML file. The program itself is reasonably simple and is shown in
Example 20-7. SAXLister.java
public
public class
class
SAXLister
SAXLister
{
final
final
boolean
boolean
DEBUG
=
false
false
;
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
Exception
{
new
new
SAXLister
(
args
);
}
public
public
SAXLister
(
String
[]
args
)
throws
throws
SAXException
,
IOException
{
XMLReader parser
=
XMLReaderFactory
.
createXMLReader
();
parser
.
setContentHandler
(
new
new
PeopleHandler
());
parser
.
parse
(
args
.
length
==
1
?
args
[
0
] :
"xml/people.xml"
);
}
/** Inner class provides DocumentHandler
*/
class
class
PeopleHandler
PeopleHandler
extends
extends
DefaultHandler
{
boolean
boolean
person
=
false
false
;
boolean
boolean
email
=
false
false
;
public
public
void
void
startElement
(
String nsURI
,
String localName
,
String rawName
,
Attributes attributes
)
throws
throws
SAXException
{
iif
(
DEBUG
) {
System
.
out
.
println
(
"startElement: "
+
localName
+
","
+
rawName
);
}
// Consult rawName since we aren't using xmlns prefixes here.
iif
(
rawName
.
equalsIgnoreCase
(
"name"
))
person
=
true
true
;
iif
(
rawName
.
equalsIgnoreCase
(
"email"
))
email
=
true
true
;
}
public
public
void
void
characters
(
char
char
[]
ch
,
int
int
start
,
int
int
length
) {
iif
(
person
) {