01: package org.uispec4j.xml;
02:
03: import org.xml.sax.Attributes;
04: import org.xml.sax.InputSource;
05: import org.xml.sax.SAXException;
06: import org.xml.sax.helpers.DefaultHandler;
07:
08: import javax.xml.parsers.ParserConfigurationException;
09: import javax.xml.parsers.SAXParser;
10: import javax.xml.parsers.SAXParserFactory;
11: import java.io.Reader;
12: import java.util.Stack;
13:
14: class SaxParser extends DefaultHandler {
15:
16: private Stack nodesStack = new Stack();
17: private SAXParser parser;
18: private StringBuffer charBuffer;
19:
20: public SaxParser() {
21: try {
22: SAXParserFactory saxParserFactory = SAXParserFactory
23: .newInstance();
24: saxParserFactory.setNamespaceAware(true);
25: parser = saxParserFactory.newSAXParser();
26: } catch (ParserConfigurationException e) {
27: throw new RuntimeException(e);
28: } catch (SAXException e) {
29: throw new RuntimeException(e);
30: }
31: charBuffer = new StringBuffer();
32: }
33:
34: public void parse(Node rootNode, Reader reader)
35: throws RuntimeException {
36: nodesStack.clear();
37: nodesStack.push(rootNode);
38: try {
39: parser.parse(new InputSource(reader), this );
40: rootNode.complete();
41: } catch (Exception e) {
42: throw new RuntimeException(e);
43: }
44: }
45:
46: public void startElement(String uri, String local, String qName,
47: Attributes atts) {
48: charBuffer.setLength(0);
49: Node currentNode = (Node) nodesStack.peek();
50: Node child;
51: try {
52: child = currentNode.getSubNode(local, atts);
53: } catch (RuntimeException e) {
54: child = SilentNode.INSTANCE;
55: }
56: if (child == null) {
57: throw new NullPointerException();
58: } else {
59: nodesStack.push(child);
60: }
61: }
62:
63: public void characters(char[] chars, int start, int length)
64: throws SAXException {
65: charBuffer.append(chars, start, length);
66: }
67:
68: public void endElement(String uri, String localName, String qName)
69: throws SAXException {
70: Node previousNode = ((Node) nodesStack.peek());
71: previousNode.setValue(charBuffer.toString());
72: charBuffer.setLength(0);
73: Node node = (Node) nodesStack.pop();
74: node.complete();
75: }
76: }
|