如何用java代码(Dom4j),通过XSD文件,对XML进行验证

在XMLSpy中,我们知道如何手动对一个XML文件进行XSD验证,那么如何通过代码进行验证呢?并返回错误信息呢

以下代码给出一种具体的方法

首先在POM中添加以下依赖


		
			dom4j
			dom4j
			1.6.1
		
		
			jaxen
			jaxen
			1.1.4
		

然后具体方法参照如下

    String SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
	
	String XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
	
	String SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
	
	String FILE_PREFIX = "file:";
	
	String ATTRIBUTE_LINE = "line";		
        StringBuilder errorMsg = new StringBuilder();
		try {
			XMLErrorHandler errorHandler = new XMLErrorHandler();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setValidating(true);
			factory.setNamespaceAware(true);
			SAXParser parser = factory.newSAXParser();
			Document xmlDocument = document;
			parser.setProperty(SCHEMA_LANGUAGE, XML_SCHEMA);
			parser.setProperty(SCHEMA_SOURCE, FILE_PREFIX + xsdFileName);
			SAXValidator validator = new SAXValidator(parser.getXMLReader());
			validator.setErrorHandler(errorHandler);
			validator.validate(xmlDocument);
			if (errorHandler.getErrors().hasContent()) {
				List elements = errorHandler.getErrors().elements();
				for (Element element : elements) {
					String line = String.valueOf(Integer.parseInt(element.attributeValue(ATTRIBUTE_LINE)) - 1);
					String text = element.getText();
					errorMsg.append("(第 " + line + "行出现错误) " + text);
				}
				errorMsg.append("XML文件通过XSD文件校验失败!");
			} 
		} catch (SAXException | ParserConfigurationException e) {
			logger.error("验证出现异常!",e);
			errorMsg.append("验证出现异常!" + e.getMessage());
		}
		return errorMsg.toString();

 

你可能感兴趣的:(Dom4j,XML,XSD验证)