美文网首页
Java 使用 XSD 校验 XML

Java 使用 XSD 校验 XML

作者: 青丝如梦 | 来源:发表于2019-05-09 10:26 被阅读0次

    原文地址:
    https://www.journaldev.com/895/how-to-validate-xml-against-xsd-in-java

    
    package com.journaldev.xml;
    
    import java.io.File;
    import java.io.IOException;
    
    import javax.xml.XMLConstants;
    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;
    
    import org.xml.sax.SAXException;
    
    public class XMLValidation {
    
        public static void main(String[] args) {
            System.out.println("EmployeeRequest.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeRequest.xml"));
            System.out.println("EmployeeResponse.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "EmployeeResponse.xml"));
            System.out.println("employee.xml validates against Employee.xsd? "+validateXMLSchema("Employee.xsd", "employee.xml"));
        }
        
        public static boolean validateXMLSchema(String xsdPath, String xmlPath){
            try {
                SchemaFactory factory = 
                        SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                Schema schema = factory.newSchema(new File(xsdPath));
                Validator validator = schema.newValidator();
                validator.validate(new StreamSource(new File(xmlPath)));
            } catch (IOException | SAXException e) {
                System.out.println("Exception: "+e.getMessage());
                return false;
            }
            return true;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Java 使用 XSD 校验 XML

          本文链接:https://www.haomeiwen.com/subject/sdiioqtx.html