public static bool validateXml(string strXml, string strXsdFilePath) { bool validity = false; try { //step 1: Read the XSD file and create xml schema object from it StreamReader xsdReader = new StreamReader(strXsdFilePath); XmlSchema schema = new XmlSchema(); schema = XmlSchema.Read(xsdReader, new ValidationEventHandler(XSDValidationEventHandler)); //step 2: Instantiate xml reader settings so that xml file //is actually read according to the configured settings XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas.Add(schema); readerSettings.ValidationEventHandler += new ValidationEventHandler(XMLValidationEventHandler); //step 3: Read and validate xml file StringReader xmlReader = new StringReader(strXml); XmlReader objXmlReader = XmlReader.Create(xmlReader, readerSettings); while (objXmlReader.Read()) { } //if at this point, then xml has been validated against the xsd file validity = true; //log the success log.Info("Successfule xml file validation"); } catch (Exception error) { validity = false; // XML Validation failed log.Error( "XML validation failed:- ERROR MESSAGE: " + error.Message); } return validity; }
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="CRS_Test.dtd" xmlns:wmh="http://www.wmhelp.com/2003/eGenerator" elementformdefault="qualified" targetnamespace="CRS_Test.dtd"> <xs:element name="TEST"> <xs:complextype /> </xs:element> </xs:schema>
my XML File <test> </test>
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)