XML validation does not require the generation of generated classes. Let's look at this helper class:
public class Validator { XmlSchemaSet schemaset; ILog logger; static Validator instance; static object lockObject = new Object(); public static Validator Instance { get { return instance; } } public Validator(string schemaPath) { WarningAsErrors = true; logger = LogManager.GetLogger(GetType().Name); schemaset = new XmlSchemaSet(); foreach (string s in Directory.GetFiles(schemaPath, "*.xsd")) { schemaset.Add(XmlSchema.Read(XmlReader.Create(s),new ValidationEventHandler((ss,e)=>OnValidateReadSchema(ss,e)))); } instance = this; } private void OnValidateReadSchema(object ss, ValidationEventArgs e) { if (e.Severity == XmlSeverityType.Error) logger.Error(e.Message); else logger.Warn(e.Message); } public bool WarningAsErrors { get; set; } private string FormatLineInfo(XmlSchemaException xmlSchemaException) { return string.Format(" Line:{0} Position:{1}", xmlSchemaException.LineNumber, xmlSchemaException.LinePosition); } protected void OnValidate(object _, ValidationEventArgs vae) { if (vae.Severity == XmlSeverityType.Error) logger.Error(vae.Message); else logger.Warn(vae.Message); if (vae.Severity == XmlSeverityType.Error || WarningAsErrors) errors.AppendLine(vae.Message + FormatLineInfo(vae.Exception)); else warnings.AppendLine(vae.Message + FormatLineInfo(vae.Exception)); } public string ErrorMessage { get; set; } public string WarningMessage { get; set; } StringBuilder errors, warnings; public void Validate(String doc) { lock (lockObject) { errors = new StringBuilder(); warnings = new StringBuilder(); XmlReaderSettings settings = new XmlReaderSettings(); settings.CloseInput = true; settings.ValidationEventHandler += new ValidationEventHandler((o, e) => OnValidate(o, e));
To use it, simply create an instance of Validator , passing the path where xsd is located. Then call the Validate (string) function, which passes the contents of the XML document. You will find the ErrorMessage and WarningMessage properties set with the errors / warnings found (if any). In order to work, an XML document must have an xmlns declaration. Note that my class uses log4net by default as a logging mechanism, so it will not compile as if you were not using log4net.
Felice pollano
source share