java xsd校验xml

下面使用xsd校验xml

public class XmlValidator {
	private static String errorMsg;
	public static boolean check(String xmlFile, String xsdFile){
		boolean rs = false;		
		rs = checkXSDFormat(xmlFile, xsdFile);
		return rs;
	}
		
	/**
	 * 校验	
	 */
	private static boolean checkXSDFormat(String xmlFile, String xsdFile) {
		SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
		XSDErrorHandler errorHandler = new XSDErrorHandler();
		Validator validator = null;
		try {
			Schema schema = factory.newSchema(new File(xsdFile));
			validator = schema.newValidator();			
			validator.setErrorHandler(errorHandler);
			
		} catch (SAXParseException e) {			
			errorMsg = e.getMessage();
			return false;
		} catch (SAXException e) {			
			errorMsg = e.getMessage();
			return false;
		}		
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(xmlFile);
			validator.validate(new StreamSource(fis));//new File(this.xmlFile)));
		} catch (SAXException e) {			
			errorMsg = e.getMessage();
			return false;
		} catch (IOException e) {			
			errorMsg = e.getMessage();
			return false;
		} finally {
			if(fis != null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		if(errorHandler.getError() != null){
			errorMsg = errorHandler.getError();
			return false;
		}
		return true;
	}
	
	public static String getError() {
		return errorMsg;
	}
}

 测试

public class XmlValidate {
	private static String xmlFile = "xml文件路径";
	private static String xsdFile = "对应的xsd文件路径";
	public static void main(String[] args) {
		System.out.println(XmlValidator.check(xmlFile, xsdFile));
		System.out.println(XmlValidator.getError());
	}
}

猜你喜欢

转载自shareisattitude.iteye.com/blog/2252586