# example-xsd **Repository Path**: jrunner/example-xsd ## Basic Information - **Project Name**: example-xsd - **Description**: 关于JAVA中通过XSD验证XML文件 - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2016-07-23 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 关于JAVA中通过XSD验证XML文件 java自jdk1.5以上新增了SchemaFactory类 可以实现对XSD验证的支持,使用起来也很方便。 示例: SAX方式验证xml -> JdkValidateXsdBySAX.java DOM方式验证xml -> JdkValidateXsdByDOM.java Dom4j方式验证xml -> JdkValidateXsdByDom4j.java ### DOM ### DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setSchema(schemaFactory.newSchema(new Source[] {new StreamSource("contacts.xsd")})); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new SimpleErrorHandler()); Document document = builder.parse(new InputSource("document.xml")); ### SAX ### SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setSchema(schemaFactory.newSchema(new Source[] {new StreamSource("contacts.xsd")})); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new SimpleErrorHandler()); reader.parse(new InputSource("document.xml")); ### dom4j ### SAXParserFactory factory = SAXParserFactory.newInstance(); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setSchema(schemaFactory.newSchema(new Source[] {new StreamSource("contacts.xsd")})); SAXParser parser = factory.newSAXParser(); SAXReader reader = new SAXReader(parser.getXMLReader()); reader.setValidation(false); reader.setErrorHandler(new SimpleErrorHandler()); reader.read("contacts.xml"); ### XOM ### SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setSchema(schemaFactory.newSchema(new Source[] {new StreamSource("contacts.xsd")})); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new SimpleErrorHandler()); Builder builder = new Builder(reader); builder.build("contacts.xml"); ### 参考资料 ### http://www.edankert.com/validate.html http://blog.csdn.net/a276202460/article/details/5483183 ### 修改记录 ### 1. 2016-07-23(周六), 完成通过XSD验证XML的合法性.