package com; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import javax.xml.XMLConstants; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; 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.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.xml.sax.SAXException; public class validateXML { /** * XSD和XML文件放在工程的bin路径下 */ public static boolean validate(String schemaLocaltion,OMElement request) throws SAXException,IOException { // 获取Schema工厂类 // 这里的XMLConstants.W3C_XML_SCHEMA_NS_URI的值就是://http://www.w3.org/2001/XMLSchema SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // 获取XSD文件,以流的方式读取到Source中 // XSD文件的位置相对于类文件位置 Source schemaSource = new StreamSource(new FileInputStream(schemaLocaltion)); Schema schema = factory.newSchema(schemaSource); // 这里是将一个DOM树对象转换成流对象,以便对DOM树对象验证 // 如果是对XML文件进行验证,用FileInputStream即可 String input = request.toString(); ByteArrayInputStream bais = new ByteArrayInputStream( input.getBytes("UTF-8")); // 获取验证器,验证器的XML Schema源就是之前创建的Schema Validator validator = schema.newValidator(); Source source = new StreamSource(bais); // 执行验证 try { validator.validate(source); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } finally { bais.close(); } } /** * get OMElement soap request from specified XML file. * * @param request * @return * @throws FileNotFoundException * @throws XMLStreamException * @throws FactoryConfigurationError */ public static OMElement getRequest(String filePath) throws FileNotFoundException,XMLStreamException,FactoryConfigurationError { XMLStreamReader reader = XMLInputFactory.newInstance() .createXMLStreamReader( new FileInputStream(new File(filePath))); StAXOMBuilder builder = new StAXOMBuilder(reader); OMElement requestMessage = builder.getDocumentElement(); return requestMessage; } public static void main(String[] args) { try { if (validate("D:\\Documents\\2014.11work\\mzyw1.xsd",getRequest("D:\\Documents\\2014.11work\\mzyw1.xml"))) { System.out.println("customer_err.xml格式良好"); } else { System.out.println("customer_err.xml格式有误,请检查!"); } } catch (Exception ex) { ex.printStackTrace(); System.out.println("文件格式有误,请检查!"); } } }