Java XML Validator validate xml file

Description

Java XML Validator validate xml file


import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
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 Main {

    public static void main(String[] args) {
       boolean valid = true;
       SchemaFactory sFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
       try {//from  w  w w .ja v a  2  s. c  o m
           Schema schema = sFactory.newSchema(new File("your schema file"));
           Validator validator = schema.newValidator();
           Source source = new StreamSource(new File("data.xml"));
           validator.validate(source);
       } catch (SAXException | IOException | IllegalArgumentException ex) {
           valid = false;
       }
       System.out.printf("XML file is %s.\n", valid ? "valid" : "invalid");
    }
}



PreviousNext

Related