Java Reference
In-Depth Information
// Called when the end of element is encountered
public void endElement(String name) throws SAXException {
// Make sure we have a matching closing element
if ( currentElement.equals(name) ) {
// Put the element/value pair into the Hashtable
table.put(currentElement, currentValue);
}
}
The endElement() method is the final event handler that we are concerned with. It is called
whenever the end of an element is encountered. If we use the same example from the
startElement() method, then endElement() would be invoked when the </ID> tag was
encountered. The overridden endElement() method takes the passed-in name and compares it
with the current element being processed. If they match, the endElement() method puts the
element and its character data into the Hashtable .
Now that you understand what happens as each event is triggered, we will return to our
XMLTest application. The remainder of our application is listed in the following code snippet:
// After the resource has been parsed get the resulting table
Hashtable cfgTable = handler.getTable();
// Print the config settings that we are interested in.
System.out.println(“ID == “ +
(String)cfgTable.get(new String(“ID”)));
System.out.println(“DESCRIPTION == “ +
(String)cfgTable.get(new String(“DESCRIPTION”)));
System.out.println(“PRICE == “ +
(String)cfgTable.get(new String(“PRICE”)));
System.out.println(“QUANTITY == “ +
(String)cfgTable.get(new String(“QUANTITY”)));
As you can see, after the parser is finished parsing, the application calls your handler's
getTable() method. This method returns a Hashtable containing the elements and their text
data that was parsed from the XML file.
The final steps you perform are printing the elements you are interested in from the parsed file.
To see this in action, compile and build the handler and application and then execute the appli-
cation with the XML file we described earlier. Your command line should be similar to the fol-
lowing:
java XMLTest item.xml
Search WWH ::




Custom Search