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.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class SchemaValidator
{
public static void main(String[] args)
{
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try
{
Schema schema = factory.newSchema(new File("C:\\myschema.xsd"));
Validator validator = schema.newValidator();
validator.setErrorHandler(new SimpleErrorHandler());
try
{
validator.validate(new StreamSource(new File("C:\\myxmldata.xml")));
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (SAXException e)
{
e.printStackTrace();
}
}
}
class SimpleErrorHandler implements ErrorHandler
{
public void warning(SAXParseException e) throws SAXException
{
System.out.println(e.getMessage());
// create problem marker
}
public void error(SAXParseException e) throws SAXException
{
System.out.println(e.getMessage());
// create problem marker
}
public void fatalError(SAXParseException e) throws SAXException
{
System.out.println(e.getMessage());
// create problem marker
}
}