📜  XSD-验证

📅  最后修改于: 2020-11-09 05:46:05             🧑  作者: Mango


我们将使用基于Java的XSD验证器来根据students.xsd来验证students.xml

students.xml



  
   
      Dinkar    
      Kad
      Dinkar
      85     
   
   
        
      Vaneet
      Gupta
      Vinni
      95
   
   
       
      Jasvir
      Singh
      Jazz
      90
   

学生.xsd




   
      
         
             
         
      
   

   
      
         
         
         
         
      
      
                

XSDValidator.java

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 XSDValidator {
   public static void main(String[] args) {
      if(args.length !=2){
         System.out.println("Usage : XSDValidator  " );
      } else {
         boolean isValid = validateXMLSchema(args[0],args[1]);
         
         if(isValid){
            System.out.println(args[1] + " is valid against " + args[0]);
         } else {
            System.out.println(args[1] + " is not valid against " + args[0]);
         }
      }
   }
   
   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 e){
         System.out.println("Exception: "+e.getMessage());
         return false;
      }catch(SAXException e1){
         System.out.println("SAX Exception: "+e1.getMessage());
         return false;
      }
        
      return true;
    
   }
}

针对XSD验证XML的步骤

  • XSDValidator.java文件复制到任何位置,例如E: > java

  • students.xml复制到同一位置E: > java

  • students.xsd复制到同一位置E: > java

  • 使用控制台编译XSDValidator.java 。确保您的计算机上已安装JDK 1.5及更高版本,并且已配置类路径。有关如何使用JAVA的详细信息,请参见JAVA教程

E:\java\javac XSDValidator.java
  • 使用作为参数传递的students.xsdstudents.xml执行XSDValidator

E:\java\java XSDValidator students.xsd students.xml

验证输出

您将看到以下结果-

students.xml is valid against students.xsd