Document parseDocument(String filename) throws Exception { FileReader reader = new FileReader(filename); String firstLine = new BufferedReader(reader).readLine(); reader.close(); Document document = null; if (firstLine.startsWith("<?xml")) { System.err.println("XML detected; using default XML parser."); } else { try { Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser"); Object parser = nekoParserClass.newInstance(); Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class}); Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]); parse.invoke(parser, filename); document = (Document) getDocument.invoke(parser); } catch (Exception e) { System.err.println("NekoHTML HTML parser not found; HTML4 support disabled."); } } if (document == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (ParserConfigurationException e) { System.err.println("Warning: Could not disable external DTD loading"); } DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(filename); } return document; }
static { try { dbf.setNamespaceAware(true); db = dbf.newDocumentBuilder(); xpath.setNamespaceContext( new NamespaceContext() { @Override public Iterator<String> getPrefixes(String namespaceURI) { return Arrays.asList("md").iterator(); } @Override public String getPrefix(String namespaceURI) { return "md"; } @Override public String getNamespaceURI(String prefix) { return "http://www.osgi.org/xmlns/metatype/v1.1.0"; } }); } catch (ParserConfigurationException e) { e.printStackTrace(); throw new ExceptionInInitializerError(e); } }
/** * Reads an XML document from an input source and copies its values into the specified object * * @param ob The object to receive the values * @param source The location of the XML document * @throws IOException If there is an error reading the document */ public void readObject(Object ob, InputSource source) throws IOException { try { // Create a document builder to read the document DocumentBuilder builder = factory.newDocumentBuilder(); // Read the document Document doc = builder.parse(source); // Get the root element Element element = doc.getDocumentElement(); // Copy the root element into the bean readObject(ob, element); } catch (SAXException exc) { throw new IOException("Error parsing XML document: " + exc.toString()); } catch (ParserConfigurationException exc) { throw new IOException("Error parsing XML document: " + exc.toString()); } }
/** Forward to real factory, set error handler */ public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { DocumentBuilder db = fact.newDocumentBuilder(); log.debug3("Created builder: " + db); db.setErrorHandler(new MyErrorHandler()); return db; }