01: /*
02: * GeoTools - OpenSource mapping toolkit
03: * http://geotools.org
04: * (C) 2002-2006, GeoTools Project Managment Committee (PMC)
05: *
06: * This library is free software; you can redistribute it and/or
07: * modify it under the terms of the GNU Lesser General Public
08: * License as published by the Free Software Foundation;
09: * version 2.1 of the License.
10: *
11: * This library is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14: * Lesser General Public License for more details.
15: */
16: package org.geotools.xml;
17:
18: import javax.xml.parsers.ParserConfigurationException;
19: import javax.xml.transform.Source;
20: import javax.xml.transform.Transformer;
21: import javax.xml.transform.TransformerConfigurationException;
22: import javax.xml.transform.TransformerException;
23: import javax.xml.transform.TransformerFactory;
24: import javax.xml.transform.dom.DOMSource;
25: import javax.xml.transform.sax.SAXResult;
26:
27: import org.geotools.xml.impl.ParserHandler;
28: import org.w3c.dom.Document;
29: import org.xml.sax.SAXException;
30:
31: /**
32: * Parses a DOM (Document Object Model) using the geotools xml binding system.
33: *
34: * @author Justin Deoliveira, The Open Planning Project
35: *
36: */
37: public class DOMParser {
38: Configuration configuration;
39: Document document;
40: ParserHandler handler;
41:
42: /**
43: * Creates a new instance of the parser.
44: *
45: * @param configuration Object representing the configuration of the parser.
46: * @param document An xml document.
47: *
48: */
49: public DOMParser(Configuration configuration, Document document) {
50: this .configuration = configuration;
51: this .document = document;
52: }
53:
54: /**
55: * Parses the supplied DOM returning a single object respresenting the
56: * result of the parse.
57: *
58: * @return The object representation of the root element of the document.
59: *
60: * @throws ParserConfigurationException
61: * @throws SAXException
62: */
63: public Object parse() throws ParserConfigurationException,
64: SAXException {
65: //Prepare the DOM source
66: Source source = new DOMSource(document);
67:
68: // Create the handler to handle the SAX events
69: handler = new ParserHandler(configuration);
70:
71: try {
72: // Prepare the result
73: SAXResult result = new SAXResult(handler);
74:
75: TransformerFactory xformerFactory = TransformerFactory
76: .newInstance();
77:
78: // Create a transformer
79: Transformer xformer = xformerFactory.newTransformer();
80:
81: // Traverse the DOM tree
82: xformer.transform(source, result);
83: } catch (TransformerConfigurationException e) {
84: new ParserConfigurationException().initCause(e);
85: } catch (TransformerException e) {
86: throw new SAXException(e);
87: }
88:
89: return handler.getValue();
90: }
91: }
|