| CartDocumentHandler.java |
package xml;
import java.util.Vector;
import net.Cart;
import net.Product;
import org.xml.sax.helpers.DefaultHandler;
/**
* The CartDocumentHandler gets notification in
* the form of a call-back method. These
* call-backs are like the Listener model
* used for event handling. When a new element
* is encountered, for example, that creates
* a call-back. The call-backs are handled
* in the DocumentHandler:
*/
public class CartDocumentHandler
extends DefaultHandler {
private Cart c = new Cart();
private Vector stringVector = new Vector();
public Cart getCart() {
return c;
}
/**
* The Locator instance must be
* used locally to identify
* the origin of a SAX event.
*/
//public void setDocumentLocator(Locator l) {
//}
// public void startDocument()
// throws SAXException {
// }
// public void endDocument()
// throws SAXException {
//}
/** The AttributeList is not
* going to have any attributes
* in it for our example (i.e.
* <book isbn=10> provides an
* attribute of isbn whose value is 10).
*/
public void startElement() {
}
/**
* When we get the </Product> tag, then
* we want to invoke
* addProduct otherwise, just return:
*/
public void endElement(String name) {
if (!name.equals("Product")) return;
addProduct();
}
/**
* addProduct will
* make an instance of a
* Product class and add it to the
* Cart instance. It is added by parsing
* the last three strings that
* have been pushed into the StringVector.
*/
public void addProduct() {
String sa[] = new String[stringVector.size()];
stringVector.copyInto(sa);
if (sa.length < 3) return;
String name = sa[0];
float price = Float.valueOf(sa[1]).floatValue();
int productId = Integer.valueOf(sa[2]).intValue();
Product p
= new Product(name, price, productId);
c.addProduct(p);
stringVector = new Vector();
}
/**
*
* when characters are found, we add them to
* the string vector for latter use.
*/
public void characters(char buf [], int offset, int len) {
stringVector.addElement(new String(buf, offset, len));
}
public void ignorableWhitespace(
char buf [], int offset, int len) {
}
/**
* The processingInstruction is
* called back when a non XML
* declaration is made.
*/
public void processingInstruction(
String target,
String data) {
}
}