using System; using System.Collections; using System.Data; using System.IO; using System.Xml; using System.Xml.Schema; using System.Text; class XMLValidator { static StringBuilder errBuilder; public static bool ValidateXML(string xmlFile, string xsdFile) { errBuilder = new StringBuilder(); XmlSchemaSet xs = new XmlSchemaSet(); xs.Add(null, xsdFile); XmlReader reader = null; XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationEventHandler += new ValidationEventHandler(BlogSettingsValidationEventHandler); settings.ValidationType = ValidationType.Schema; settings.Schemas = xs; reader = XmlReader.Create(xmlFile, settings); while (reader.Read()) { } return (errBuilder.ToString() == String.Empty); } private static void BlogSettingsValidationEventHandler(object sender, ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Warning e.Severity == XmlSeverityType.Error) { errBuilder.Append("Error"); //errBuilder.Append(e.Message); } } }
To invoke the method, do something like below:
if (XMLValidator.ValidateXML(xmlFile, xsdFile)) { // Good } else { // Bad }
Have fun!
No comments:
Post a Comment
Do provide your constructive comment. I appreciate that.