Example usage for javax.xml.parsers DocumentBuilderFactory setSchema

List of usage examples for javax.xml.parsers DocumentBuilderFactory setSchema

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setSchema.

Prototype

public void setSchema(Schema schema) 

Source Link

Document

Set the Schema to be used by parsers created from this factory.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File("data.xsd"));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/* w ww.ja va 2 s. c  o  m*/
    dbf.setSchema(schema);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File("data.xml"));

    Element result = document.getElementById("abc");
    System.out.println(result);
}

From source file:Main.java

private static DocumentBuilder newDocumentBuilder(Schema schema, boolean isNamespaceAware,
        boolean isXIncludeAware) throws SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(isNamespaceAware);
    factory.setXIncludeAware(isXIncludeAware);
    if (schema != null) {
        factory.setSchema(schema);
        factory.setValidating(false);/*from  w ww.  j a v  a 2s  . com*/
    }
    DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        // there is something seriously wrong
        throw new RuntimeException(ex);
    }
    return builder;
}

From source file:hadoopInstaller.io.XMLDocumentReader.java

public static Document parse(FileObject xmlDocument, FileObject xsdDocument)
        throws InstallerConfigurationParseError {

    try {/*from w ww  .j  a v a2s .com*/
        // Validate against XML Schema
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new StreamSource(xsdDocument.getContent().getInputStream()));
        dbf.setValidating(false);
        dbf.setSchema(schema);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(new ParseErrorHandler());
        return db.parse(xmlDocument.getContent().getInputStream());
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new InstallerConfigurationParseError(e, "XMLDocumentReader.ParseError", xmlDocument.getName()); //$NON-NLS-1$
    }
}

From source file:edu.lternet.pasta.common.XmlUtility.java

/**
 * Parses the provided XML string as a (DOM) document.
 *
 * @param xmlString the XML string to be parsed.
 * @param schema the schema used to validate the provided XML.
 *
 * @return a document derived from the provided XML string.
 *///w w  w .  j  av  a  2  s. co m
public static Document xmlStringToDoc(String xmlString, Schema schema) {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setSchema(schema);

    InputSource source = new InputSource(new StringReader(xmlString));

    try {

        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new XmlParsingErrorHandler(xmlString));
        return builder.parse(source);

    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e); // shouldn't be reached
    } catch (SAXException e) {
        throw new IllegalStateException(e); // shouldn't be reached
    } catch (IOException e) {
        throw new IllegalStateException(e); // shouldn't be reached
    }

}

From source file:com.mingo.parser.xml.dom.DocumentBuilderFactoryCreator.java

/**
 * Creates DocumentBuilderFactory.//from   w w w. j  a  v  a 2s . com
 *
 * @param parserConfiguration {@link ParserConfiguration}
 * @return DocumentBuilderFactory a factory API that enables applications to obtain a
 *         parser that produces DOM object trees from XML documents
 * @throws ParserConfigurationException {@link ParserConfigurationException}
 */
public static DocumentBuilderFactory createDocumentBuilderFactory(ParserConfiguration parserConfiguration)
        throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setValidating(parserConfiguration.isValidate());
    documentBuilderFactory.setNamespaceAware(parserConfiguration.isNamespaceAware());
    documentBuilderFactory.setFeature(DYNAMIC_VALIDATION, true);
    List<Source> sourceList = createSchemaSources(parserConfiguration.getXsdSchemaPaths());
    if (CollectionUtils.isNotEmpty(sourceList)) {
        documentBuilderFactory.setSchema(createSchema(sourceList));
    }
    return documentBuilderFactory;
}

From source file:AndroidUninstallStock.java

public static DocumentBuilderFactory getXmlDocFactory() throws SAXException {
    DocumentBuilderFactory xmlfactory = DocumentBuilderFactory.newInstance();
    xmlfactory.setIgnoringComments(true);
    xmlfactory.setCoalescing(true);//from w  w w. ja  va2  s.  c  o  m
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4867706
    xmlfactory.setIgnoringElementContentWhitespace(true);
    xmlfactory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(AndroidUninstallStock.class.getResource("AndroidListSoft.xsd")));
    xmlfactory.setValidating(false); // not DTD
    return xmlfactory;
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Validates given XML file against an XSD schema
 *
 * @param file//  w ww.j  a  v a2  s. c  o m
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(File file, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(file);
    return errorHandler.getValidationErrors();
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Validates given document agains an XSD schema
 *
 * @param document/*from w  ww . java2s  .  c om*/
 * @param xsd
 * @return
 */
public static List<String> validateAgainstXSD(Document document, InputStream xsd) throws Exception {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    factory.setResourceResolver(MetsLSResolver.getInstance());
    Schema schema = factory.newSchema(new StreamSource(xsd));
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    DOMSource domSource = new DOMSource(document);
    StreamResult sResult = new StreamResult();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    sResult.setOutputStream(bos);
    transformer.transform(domSource, sResult);
    InputStream is = new ByteArrayInputStream(bos.toByteArray());
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setValidating(false);
    dbfactory.setNamespaceAware(true);
    dbfactory.setSchema(schema);
    DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler();
    documentBuilder.setErrorHandler(errorHandler);
    documentBuilder.parse(is);
    return errorHandler.getValidationErrors();
}

From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java

/**
 * Creates the export study response.//from  ww  w .  j  a v  a2s  .co  m
 *
 * @param study the study
 * @return the sOAP message
 * @throws SOAPException the sOAP exception
 * @throws XMLUtilityException the xML utility exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws SAXException the sAX exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private SOAPMessage createExportStudyResponse(Study study)
        throws SOAPException, XMLUtilityException, ParserConfigurationException, SAXException, IOException {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage response = mf.createMessage();
    SOAPBody body = response.getSOAPBody();
    SOAPElement exportStudyResponse = body.addChildElement(new QName(SERVICE_NS, "ExportStudyResponse"));
    String xml = marshaller.toXML(study);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(XmlMarshaller.class.getResource(C3PR_DOMAIN_XSD_URL)));
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml));
    Element studyEl = (Element) doc.getFirstChild();
    exportStudyResponse.appendChild(body.getOwnerDocument().importNode(studyEl, true));
    response.saveChanges();
    return response;
}

From source file:com.ebay.jetstream.event.processor.esper.raw.EsperTestConfigurationValidator.java

public boolean validate(String instance, String schema) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {//from   ww  w. jav a 2s .c  o  m
        warnings = 0;
        errors = 0;
        fatalErrors = 0;
        try {
            //Set the validation feature
            factory.setFeature("http://xml.org/sax/features/validation", true);

            //Set the schema validation feature
            factory.setFeature("http://apache.org/xml/features/validation/schema", true);

            //Set schema full grammar checking
            factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

            // If there is an external schema set it
            if (schema != null) {
                SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                Schema s = sf.newSchema(new StreamSource(schema));
                factory.setSchema(s);
            }
            DocumentBuilder parser = factory.newDocumentBuilder();
            parser.setErrorHandler(this);
            // Parse and validate
            parser.parse(instance);
            // Return true if we made it this far with no errors
            return ((errors == 0) && (fatalErrors == 0));
        } catch (SAXException e) {
            log.error("Could not activate validation features - " + e.getMessage());
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return false;
}