Search in sources :

Example 1 with XMLErrorHandler

use of org.dom4j.util.XMLErrorHandler in project wechat by dllwh.

the class XmlUtils method validateBySchema.

/**
 * 检验指定的XML是否符合
 *
 * @param doc
 *            被检验的XML文档
 * @param schemePath
 *            schema的路径
 * @return 如果出错,返回错误信息,否则返回null
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws DocumentException
 */
public static String validateBySchema(Document doc, String schemePath) throws ParserConfigurationException, SAXException, DocumentException {
    XMLErrorHandler errorHandler = new XMLErrorHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    SAXParser parser = factory.newSAXParser();
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + schemePath);
    SAXValidator validator = new SAXValidator(parser.getXMLReader());
    validator.setErrorHandler(errorHandler);
    if (errorHandler.getErrors().hasContent()) {
        return errorHandler.getErrors().asXML();
    }
    return null;
}
Also used : XMLErrorHandler(org.dom4j.util.XMLErrorHandler) SAXParser(javax.xml.parsers.SAXParser) SAXValidator(org.dom4j.io.SAXValidator) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

SAXParser (javax.xml.parsers.SAXParser)1 SAXParserFactory (javax.xml.parsers.SAXParserFactory)1 SAXValidator (org.dom4j.io.SAXValidator)1 XMLErrorHandler (org.dom4j.util.XMLErrorHandler)1