Java Reference
In-Depth Information
int getLength() : Returns a count of the number of attributes encapsulated in the Attributes
object.
String getLocalName(int index) : Returns a string containing the local name of the attribute
for the index value passed as the argument.
String getQName(int index) : Returns a string containing the XML 1.0 qualified name of the
attribute for the index value passed as the argument.
String getType(int index) : Returns a string containing the type of the attribute for the
index value passed as the argument. The type is returned as one of the following: "CDATA" , "ID" ,
"IDREF" , "IDREFS" , "NMTOKEN" , “ NMTOKENS" , "ENTITY" , "ENTITIES" , "NOTATION"
String getValue(int index) : Returns a string containing the value of the attribute for the in-
dex value passed as the argument.
String getURI(int index) : Returns a string containing the attribute's namespace URI, or an
empty string if no URI is available.
If the index value that you supply to any of these getXXX() methods here is out of range, then the method
returns null .
Given a reference, attr , of type Attributes , you can retrieve information about all the attributes with
the following code:
int attrCount = attr.getLength();
if(attrCount>0) {
System.out.println("Attributes:");
for(int i = 0 ; i < attrCount ; ++i ) {
System.out.println(" Name : " + attr.getQName(i));
System.out.println(" Type : " + attr.getType(i));
System.out.println(" Value: " + attr.getValue(i));
}
}
This is very straightforward. You look for data on attributes only if the value returned by the
getLength() method is greater than zero. You then retrieve information about each attribute in the for
loop.
The DefaultHandler class is just like the adapter classes you have used for defining GUI event handlers.
To implement your own handler class you just extend the DefaultHandler class and define your own im-
plementations for the methods that you are interested in. The same caveat applies here that applied with
adapter classes — you must be sure that the signatures of your methods are correct. The best way to do this
is to use the @Override annotation. Let's try implementing a handler class.
TRY IT OUT: Handling Parsing Events
Let's first define a handler class to deal with document parsing events. You just implement a few of the
methods from the ContentHandler interface in this — only those that apply to a very simple document
— and you don't need to worry about errors for the moment. Here's the code:
Search WWH ::




Custom Search