Java XML Validator validate Document

Description

Java XML Validator validate Document

import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;

public class Main {
   public static void main(String args[]) {
      try {//  w  w w  .j  av a2  s . c o  m
         String xmlFile = args[0], schemaFile = args[1];
         // build an XSD-aware SchemaFactory
         SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

         // get the xsd schema specifying the required format for the XML files.
         Schema schemaXSD = schemaFactory.newSchema(new File(schemaFile));

         // Get a Validator that can validate XML files according to the schema.
         Validator validator = schemaXSD.newValidator();

         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         // Get a parser capable of parsing XML into a DOM tree
         DocumentBuilder parser = factory.newDocumentBuilder();

         // parse the XML purely as XML and get a DOM tree representation.
         Document document = parser.parse(new File(xmlFile));

         // parse the XML DOM tree agaist the XSD schema
         validator.validate(new DOMSource(document));
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related