/** * Parses content of an <code>InputSource</code> to create an XML <code>Element</code> object. * * @param source the input source that is supposed to contain XML to be parsed, not <code>null * </code>. * @return the parsed result, not <code>null</code>. * @throws IOException if there is an I/O error. * @throws ParseException if the content is not considered to be valid XML. */ private Element parse(InputSource source) throws IOException, ParseException { // TODO: Consider using an XMLReader instead of a SAXParser // Initialize our SAX event handler Handler handler = new Handler(); try { // Let SAX parse the XML, using our handler SAXParserProvider.get().parse(source, handler); } catch (SAXException exception) { // TODO: Log: Parsing failed String exMessage = exception.getMessage(); // Construct complete message String message = "Failed to parse XML"; if (TextUtils.isEmpty(exMessage)) { message += '.'; } else { message += ": " + exMessage; } // Throw exception with message, and register cause exception throw new ParseException(message, exception, exMessage); } Element element = handler.getElement(); return element; }
/** * Parses content of a file to create an XML <code>Element</code> object. * * @param file the file that is supposed to contain XML to be parsed, not <code>null</code>. * @return the parsed result, not <code>null</code>. * @throws IllegalArgumentException if <code>file == null</code>. * @throws IOException if there is an I/O error, e.g. the file does not exist or is actually a * directory. * @throws ParseException if the content of the file is not considered to be valid XML. * @since XINS 2.2 */ public Element parse(File file) throws IllegalArgumentException, IOException, ParseException { // Check preconditions MandatoryArgumentChecker.check("file", file); FileInputStream fis = null; try { fis = new FileInputStream(file); return parse(fis); // Enrich an I/O exception with the file name } catch (IOException cause) { IOException e = new IOException( "Failed to parse file " + TextUtils.quote(file.getAbsolutePath()) + " due to an I/O error."); e.initCause(cause); throw e; // Enrich a parse exception with the file name } catch (ParseException cause) { throw new ParseException( "Failed to parse file " + TextUtils.quote(file.getAbsolutePath()) + '.', cause); // Anyway, always attempt to close the input stream } finally { try { if (fis != null) { fis.close(); } } catch (IOException ex) { // Never mind } } }