简体   繁体   中英

Validate XML Against XSD

Looking for some confirmation that the below is the most efficient Java solution to validate a XML String against a schema. Any other ways which are more efficient memory or performance wise?

private boolean isXMLValid(String XSDPath, String XML) {
        final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            final Schema schema = factory.newSchema(new File(XSDPath));
            final Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new ByteArrayInputStream(XML.getBytes())));
        } catch (IOException | SAXException e) {
            System.out.println("Exception: " + e.getMessage());
            return false;
        }
        return true;
    }

Hardly. You may get some minor improvements by reusing SchemaFactory (attention: not thread-safe) and Schema (immutable, thread-safe), but it's almost it. If you switch from String XML to something more streamy and use StAX you may get some memory improvements as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM