Validating an XML file with Schema in .NET 2.9
1. Read the XML file content as Stream, TextReader or XmlReader.
2. Read the Schema file content as Stream, TextReader or XmlReader.
3. Create a new instance of XmlSchema object.
4. Set XmlSchema object by calling XmlSchema.Read() method and passing the content of Schema file and ValidationEventHandler method address to it.
5. Create a new instance of XmlReaderSettings object.
6. Set ValidationType for XmlReaderSettings object to Schema.
7. Add your XmlSchema object to XmlReaderSettings Schemas collection by calling its Schemas.Add() method.
8. Add your ValidationEventHandler method address to XmlValidationReader's ValidationEventHandler handler.
9. Create a new instance of XmlReader object and pass your XML file content (as Stream or a Reader object) and XmlReaderSettings object to it.
10. Call Read() method of the Reader or Stream object to contain your XML file content in a loop to parse and validate it completely.
11. Add your logic to ValidationEventHandler method you created to implement what you want to be done in the validation process.
private void ValidatingProcess(string XSDPath, string XMLPath)
{
try
{
// 1- Read XML file content
this.Reader = new XmlTextReader(XMLPath);
// 2- Read Schema file content
StreamReader SR = new StreamReader(XSDPath);
// 3- Create a new instance of XmlSchema object
XmlSchema Schema = new XmlSchema();
// 4- Set Schema object by calling XmlSchema.Read() method
Schema = XmlSchema.Read(SR,
new ValidationEventHandler(ReaderSettings_ValidationEventHandler));
// 5- Create a new instance of XmlReaderSettings object
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
// 6- Set ValidationType for XmlReaderSettings object
ReaderSettings.ValidationType = ValidationType.Schema;
// 7- Add Schema to XmlReaderSettings Schemas collection
ReaderSettings.Schemas.Add(Schema);
// 8- Add your ValidationEventHandler address to
// XmlReaderSettings ValidationEventHandler
ReaderSettings.ValidationEventHandler +=
new ValidationEventHandler(ReaderSettings_ValidationEventHandler);
// 9- Create a new instance of XmlReader object
XmlReader objXmlReader = XmlReader.Create(Reader, ReaderSettings);
// 10- Read XML content in a loop
while (objXmlReader.Read())
{ /*Empty loop*/}
}//try
// Handle exceptions if you want
catch (UnauthorizedAccessException AccessEx)
{
throw AccessEx;
}//catch
catch (Exception Ex)
{
throw Ex;
}//catch
}
private void ReaderSettings_ValidationEventHandler(object sender,
ValidationEventArgs args)
{
// 11- Implement your logic for each validation iteration
string strTemp;
strTemp = "Line: " + this.Reader.LineNumber + " - Position: "
+ this.Reader.LinePosition + " - " + args.Message;
this.Results.Add(strTemp);
}








