+ public static Document read(String aDocument) throws XMLException {
+ ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes());
+ return read(is);
+ }
+
+ /**
+ * Parses an XML document from a stream.
+ *
+ * @param aIs
+ * Input stream.
+ * @return
+ */
+ public static Document read(InputStream aIs) throws XMLException {
+ try {
+ DocumentBuilder builder = DocumentBuilderFactory.newInstance()
+ .newDocumentBuilder();
+ return builder.parse(aIs);
+ } catch (SAXException e) {
+ throw new XMLException(e.getMessage(), e);
+ } catch (IOException e) {
+ throw new XMLException(e.getMessage(), e);
+ } catch (ParserConfigurationException e) {
+ throw new XMLException(e.getMessage(), e);
+ } finally {
+ try {
+ aIs.close();
+ } catch (Exception e) {
+ LOG.warn("Error closing XML file", e);
+ }
+ }
+ }
+
+ /**
+ * Reads and validates a document against a schema.
+ *
+ * @param aIs
+ * Input stream.
+ * @param aSchema
+ * Schema.
+ * @return Parsed and validated document.
+ */
+ public static Document readAndValidate(InputStream aIs, InputStream aSchema)
+ throws XMLException {
+
+ try {
+ final Schema schema = SchemaFactory.newInstance(
+ XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
+ new StreamSource(aSchema));
+
+ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setValidating(true);
+ factory.setNamespaceAware(true);
+ factory.setSchema(schema);
+
+ return factory.newDocumentBuilder().parse(aIs);
+ } catch (SAXException e) {
+ throw new XMLException(e.getMessage(), e);
+ } catch (IOException e) {
+ throw new XMLException(e.getMessage(), e);
+ } catch (ParserConfigurationException e) {
+ throw new XMLException(e.getMessage(), e);
+ } finally {
+ try {
+ aSchema.close();
+ } catch (Exception e) {
+ LOG.warn("Error closing schema", e);
+ }
+ try {
+ aIs.close();
+ } catch (Exception e) {
+ LOG.warn("Error closing XML file", e);
+ }
+ }
+