import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class DomValidator {
static final String schemaSource = "c:\\testProject\\mainInfo.xsd";
static final String xml_file = "c:\\testProject\\profile.xml";
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
public static void main(String args[]) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute(JAXP_SCHEMA_LANGUAGE,
"http://www.w3.org/2001/XMLSchema");
factory.setAttribute(JAXP_SCHEMA_SOURCE, new File(schemaSource));
DocumentBuilder domParser = factory.newDocumentBuilder();
// Set Error Handler
ErrorChecker errors = new ErrorChecker();
domParser.setErrorHandler(errors);
Document document = domParser.parse(new File(xml_file));
List errorList = errors.getErrors();
Iterator iter = errorList.iterator();
while (iter.hasNext()) {
String errroMessage = (String) iter.next();
System.out.println(errroMessage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// to capture the errors and warnings and the fatal errors occured
class ErrorChecker extends DefaultHandler
{
public ArrayList errorList = new ArrayList();
public ErrorChecker() {
}
public List getErrors() {
return errorList;
}
public void error(SAXParseException e) {
errorList.add("Error : " + e.getMessage() + " " + e.getPublicId() + " "
+ e.getSystemId());
}
public void warning(SAXParseException e) {
errorList.add("Warning : " + e.getMessage());
}
public void fatalError(SAXParseException e) {
errorList.add("Fatal error : " + e.getMessage());
System.exit(1);
}
}