How to use XSD2CODE generated C # classes

I am new to the XSD world, I have worked with XML, but not much programmatically. I have successfully generated C # classes using XSD2Code.Can anyone please name me how can I use these generated classes using C # and use my XML for validation.

The code snippet would be much appreciated.

Thank you and welcome.

+1
source share
2 answers

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)); // Your callback... settings.ValidationType = ValidationType.Schema; settings.Schemas.Add(schemaset); settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation; // Wrap document in an XmlNodeReader and run validation on top of that try { using (XmlReader validatingReader = XmlReader.Create(new StringReader(doc), settings)) { while (validatingReader.Read()) { /* just loop through document */ } } } catch (XmlException e) { errors.AppendLine(string.Format("Error at line:{0} Posizione:{1}", e.LineNumber, e.LinePosition)); } ErrorMessage = errors.ToString(); WarningMessage = warnings.ToString(); } } } 

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.

+1
source

Looking at the generated Serialize and Deserialize Xsd2Code methods, it does not look like schema validation. I did not use Xsd2Code much, so I could be wrong.

But you can use the XmlReaderSettings class to customize the schemas that XML will use.

 // Load the Schema Into Memory. The Error handler is also presented here. StringReader sr = new StringReader(File.ReadAllText("schemafile.xsd")); XmlSchema sch = XmlSchema.Read(sr,SchemaErrorsHandler); // Create the Reader settings. XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas.Add(sch); // Create an XmlReader specifying the settings. StringReader xmlData = new StringReader(File.ReadAllText("xmlfile.xml")); XmlReader xr = XmlReader.Create(xmlData,settings); // Use the Native .NET Serializer (probably u cud substitute the Xsd2Code serializer here. XmlSerializer xs = new XmlSerializer(typeof(SerializableClass)); var data = xs.Deserialize(xr); 
0
source

All Articles