1 8 package org.apache.avalon.excalibur.xml; 9 10 import org.apache.avalon.framework.logger.AbstractLogEnabled; 11 import org.apache.avalon.framework.thread.SingleThreaded; 12 import org.apache.xerces.parsers.DOMParser; 13 import org.apache.xerces.parsers.SAXParser; 14 import org.w3c.dom.Document ; 15 import org.xml.sax.ContentHandler ; 16 import org.xml.sax.ErrorHandler ; 17 import org.xml.sax.InputSource ; 18 import org.xml.sax.SAXException ; 19 import org.xml.sax.SAXParseException ; 20 import org.xml.sax.ext.LexicalHandler ; 21 import java.io.IOException ; 22 23 29 public class XercesParser 30 extends AbstractLogEnabled 31 implements Parser, ErrorHandler , SingleThreaded { 32 33 34 final SAXParser parser; 35 36 public XercesParser () 37 throws SAXException { 38 this.parser = new SAXParser(); 39 40 this.parser.setFeature("http://xml.org/sax/features/validation",false); 41 this.parser.setFeature("http://xml.org/sax/features/namespaces",true); 42 this.parser.setFeature("http://xml.org/sax/features/namespace-prefixes", 43 true); 44 } 45 46 public void parse(InputSource in, ContentHandler consumer) 47 throws SAXException , IOException { 48 if (consumer instanceof XMLConsumer 49 || consumer instanceof LexicalHandler ) { 50 this.parser.setProperty("http://xml.org/sax/properties/lexical-handler", 51 (LexicalHandler )consumer); 52 } 53 this.parser.setErrorHandler(this); 54 this.parser.setContentHandler(consumer); 55 this.parser.parse(in); 56 } 57 58 61 public Document parseDocument(InputSource input) throws SAXException , IOException { 62 DOMParser parser = null; 63 64 try { 65 parser = new DOMParser(); 66 67 parser.setFeature("http://xml.org/sax/features/validation",false); 68 parser.setFeature("http://xml.org/sax/features/namespaces",true); 69 parser.setFeature("http://xml.org/sax/features/namespace-prefixes", 70 true); 71 72 parser.parse(input); 73 } catch (Exception pce) { 74 getLogger().error("Could not build DocumentBuilder", pce); 75 return null; 76 } 77 78 return parser.getDocument(); 79 } 80 81 84 public void error(SAXParseException e) 85 throws SAXException { 86 throw new SAXException ("Error parsing "+e.getSystemId()+" (line "+ 87 e.getLineNumber()+" col. "+e.getColumnNumber()+ 88 "): "+e.getMessage(),e); 89 } 90 91 94 public void fatalError(SAXParseException e) 95 throws SAXException { 96 throw new SAXException ("Fatal error parsing "+e.getSystemId()+" (line "+ 97 e.getLineNumber()+" col. "+e.getColumnNumber()+ 98 "): "+e.getMessage(),e); 99 } 100 101 104 public void warning(SAXParseException e) 105 throws SAXException { 106 throw new SAXException ("Warning parsing "+e.getSystemId()+" (line "+ 107 e.getLineNumber()+" col. "+e.getColumnNumber()+ 108 "): "+e.getMessage(),e); 109 } 110 } 111 | Popular Tags |