/Users/lyon/j4p/src/xml/cart/CartDocumentHandler.java
|
1 package xml.cart;
2
3 import org.xml.sax.helpers.DefaultHandler;
4
5 import java.util.Vector;
6
7 import xml.cart.Cart;
8 import xml.Product;
9
10 /**
11 * The CartDocumentHandler gets notification in
12 * the form of a call-back method. These
13 * call-backs are like the Listener model
14 * used for event handling. When a new element
15 * is encountered, for example, that creates
16 * a call-back. The call-backs are handled
17 * in the DocumentHandler:
18
19 */
20 public class CartDocumentHandler
21 extends DefaultHandler {
22
23 private Cart c = new Cart();
24 private Vector stringVector = new Vector();
25
26 public Cart getCart() {
27 return c;
28 }
29
30 /**
31 * The Locator instance must be
32 * used locally to identify
33 * the origin of a SAX event.
34 */
35 //public void setDocumentLocator(Locator l) {
36 //}
37
38 // public void startDocument()
39 // throws SAXException {
40 // }
41
42 // public void endDocument()
43 // throws SAXException {
44 //}
45
46 /** The AttributeList is not
47 * going to have any attributes
48 * in it for our example (i.e.
49 * <book isbn=10> provides an
50 * attribute of isbn whose value is 10).
51 */
52 public void startElement() {
53 }
54
55 /**
56 * When we get the </Product> tag, then
57 * we want to invoke
58 * addProduct otherwise, just return:
59 */
60 public void endElement(String name) {
61 if (!name.equals("Product")) return;
62 addProduct();
63 }
64
65 /**
66 * addProduct will
67 * make an instance of a
68 * Product class and add it to the
69 * Cart instance. It is added by parsing
70 * the last three strings that
71 * have been pushed into the StringVector.
72 */
73 public void addProduct() {
74 String sa[] = new String[stringVector.size()];
75 stringVector.copyInto(sa);
76 if (sa.length < 3) return;
77
78 String name = sa[0];
79 float price = Float.valueOf(sa[1]).floatValue();
80 int productId = Integer.valueOf(sa[2]).intValue();
81
82 Product p
83 = new Product(name, price, productId);
84 c.addProduct(p);
85 stringVector = new Vector();
86 }
87
88 /**
89 *
90 * when characters are found, we add them to
91 * the string vector for latter use.
92 */
93 public void characters(char buf [], int offset, int len) {
94 stringVector.addElement(new String(buf, offset, len));
95 }
96
97 public void ignorableWhitespace(
98 char buf [], int offset, int len) {
99 }
100
101 /**
102 * The processingInstruction is
103 * called back when a non XML
104 * declaration is made.
105 */
106 public void processingInstruction(
107 String target,
108 String data) {
109 }
110
111 }
112