import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import javax.xml.validation.Validator;
import javax.xml.transform.dom.DOMSource;
import java.io.File;
public class XsdSchemaDomValidator {
public static void main(String[] a) {
String schemaFile = "C:/hp/OpenView/ServiceActivator/etc/config/fixed/fixed_activation_request_interface.xsd";
String inputXmlFile = "C:/Testxml/DEL_IN.xml";
XsdSchemaDomValidator schemaValidator = new XsdSchemaDomValidator();
try {
Document doc = schemaValidator.getRootDocument(schemaFile, inputXmlFile);
} catch (Exception excep) {
System.err.println("Error while trying to parse the xml :" + excep.getMessage());
}
}
public Document getRootDocument(String schemaFile, String inputXmlFile) throws Exception {
String schemaName = schemaFile;
String xmlName = inputXmlFile;
Schema schema = loadSchema(schemaName);
Document document = parseXmlDom(xmlName);
validateXml(schema, document);
return document;
}
public static void validateXml(Schema schema, Document document) throws Exception {
try {
// creating a Validator instance
Validator validator = schema.newValidator();
System.out.println();
System.out.println("Validator Class: "
+ validator.getClass().getName());
// validating the document against the schema
validator.validate(new DOMSource(document));
System.out.println();
System.out.println("Validation passed.");
} catch (Exception e) {
// catching all validation exceptions
System.out.println();
System.out.println(e.toString());
throw e;
}
}
public static Schema loadSchema(String name) throws Exception {
Schema schema = null;
try {
String language = XMLConstants.W3C_XML_SCHEMA_NS_URI;
SchemaFactory factory = SchemaFactory.newInstance(language);
schema = factory.newSchema(new File(name));
} catch (Exception e) {
System.out.println(e.toString());
throw e;
}
return schema;
}
public static Document parseXmlDom(String name) throws Exception {
Document document = null;
try {
DocumentBuilderFactory factory
= DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(new File(name));
} catch (Exception e) {
System.out.println(e.toString());
throw e;
}
return document;
}
}
إرسال تعليق