XSD - Validação

Usaremos validador XSD baseado em Java para validar students.xml contra o students.xsd.

students.xml

<?xml version = "1.0"?>

<class>  
   <student rollno = "393">
      <firstname>Dinkar</firstname>    
      <lastname>Kad</lastname>
      <nickname>Dinkar</nickname>
      <marks>85</marks>	 
   </student>
   
   <student rollno = "493">	 
      <firstname>Vaneet</firstname>
      <lastname>Gupta</lastname>
      <nickname>Vinni</nickname>
      <marks>95</marks>
   </student>
   
   <student rollno = "593">    
      <firstname>Jasvir</firstname>
      <lastname>Singh</lastname>
      <nickname>Jazz</nickname>
      <marks>90</marks>
   </student>
</class>

students.xsd

<?xml version = "1.0"?>

<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
   <xs:element name = 'class'>
      <xs:complexType>
         <xs:sequence>
             <xs:element name = 'student' type = 'StudentType' minOccurs = '0' 
                maxOccurs = 'unbounded' />
         </xs:sequence>
      </xs:complexType>
   </xs:element>

   <xs:complexType name = "StudentType">
      <xs:sequence>
         <xs:element name = "firstname" type = "xs:string"/>
         <xs:element name = "lastname" type = "xs:string"/>
         <xs:element name = "nickname" type = "xs:string"/>
         <xs:element name = "marks" type = "xs:positiveInteger"/>
      </xs:sequence>
      <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>
   </xs:complexType>			 
</xs:schema>

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 <file-name.xsd> <file-name.xml>" );
      } 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;
	
   }
}

Etapas para validar XML em relação ao XSD

  • Copie o XSDValidator.java arquivo para qualquer local, digamos E: > java

  • Copie o students.xml para o mesmo local E: > java

  • Copie o students.xsd para o mesmo local E: > java

  • Compilar XSDValidator.javausando o console. Certifique-se de ter o JDK 1.5 em diante instalado em sua máquina e os classpaths configurados. Para obter detalhes sobre como usar JAVA, consulte o Tutorial JAVA

E:\java\javac XSDValidator.java
  • Executar XSDValidator com students.xsd e students.xml passado como argumento.

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

Verifique a saída

Você verá o seguinte resultado -

students.xml is valid against students.xsd