用dom4j如何使用Schema的xsd文件验证xml文件的合法性!

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

 

 private boolean isXMLValid() {
        boolean flag = true;
        try {
            Source schemaFile = new StreamSource(

Thread. currentThread ().getContextClassLoader().getResourceAsStream( "schema/PassageReport.xsd" )

);
          
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = factory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            validator.validate(new StreamSource(new StringReader(targetXML)));
           
        } catch (Exception e) {
            flag = false;
            logger.error(e.getMessage());
        }

        return flag;
    }

你可能感兴趣的:(c,exception,xml,schema,import)