Mega Code Archive

 
Categories / C# Tutorial / XML
 

Validate Xml

using System; using System.Xml; using System.Xml.Schema; public class MainClass {   [STAThread]   private static void Main()   {       string xmlFilename = "test.xml";       string schemaFilename = "schema.xml";                  XmlReaderSettings settings = new XmlReaderSettings();         settings.ValidationType = ValidationType.Schema;         XmlSchemaSet schemas = new XmlSchemaSet();         settings.Schemas = schemas;         schemas.Add(null, schemaFilename);                  settings.ValidationEventHandler += ValidationEventHandler;              XmlReader validator = XmlReader.Create(xmlFilename, settings);                          try     {       while (validator.Read()){}     } catch (XmlException err) {       Console.WriteLine(err.Message);     } finally {       validator.Close();     }   }   private static void ValidationEventHandler(object sender, ValidationEventArgs args)   {     Console.WriteLine("Validation error: " + args.Message);   } }