In 1.x you had to follow these steps to validate an XML file
against an XSD Schema file.
1.
Read XML file content as String, XmlTextReader or Stream.
2.
Read Schema file content as Stream, TextReader or XmlReader.
3.
Create a new instance of the XmlSchema object.
4.
Set XmlSchema object by calling the XmlSchema.Read() method and passing
the content of the Schema file and ValidationEventHandler method address to it.
5. Create
a new instance of XmlValidationReader object.
6. Set
ValidationType for XmlValidationReader object to Schema.
7. Add
your XmlSchema object to XmlValidationReader Schemas collection by calling its
Schemas.Add() method.
8. Add
your ValidationEventHandler method address to XmlValidationReader's ValidationEventHandler
handler.
9. Call
Read() method of the Reader or Stream object to contain your XML file content
in a loop to parse and validate it completely.
10. Add
your logic to the ValidationEventHandler method you created to implement what
you want to be done in the validation process.
Here I have written a sample for this process. Comments
show each step in code. I read my XML file as XmlTextReader and my Schema as
Stream objects then got the line and position of each error occurrence in my
XML file structure and returned them as an ArrayList of strings. Full source
code of this class has been provided with this article.
Listing 1
private void ValidatingProcess(string XSDPath, string XMLPath)
{
try
{
// 1- Read XML file content
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 XmlSchema object by calling XmlSchema.Read() method
Schema = XmlSchema.Read(SR,
new ValidationEventHandler(ValidatingReader_ValidationEventHandler));
// 5- Create a new instance of XmlValidationReader object
XmlValidatingReader ValidatingReader = new XmlValidatingReader(Reader);
// 6- Set ValidationType for XmlValidationReader object
ValidatingReader.ValidationType = ValidationType.Schema;
// 7- Add Schema to XmlValidationReader Schemas collection
ValidatingReader.Schemas.Add(Schema);
// 8- Add your ValidationEventHandler address to
// XmlValidationReader's ValidationEventHandler
ValidatingReader.ValidationEventHandler +=
new ValidationEventHandler(ValidatingReader_ValidationEventHandler);
// 9- Read XML content in a loop
while (ValidatingReader.Read())
{/*Empty loop*/}
}// try
//Handle exceptions if you want
catch (UnauthorizedAccessException AccessEx)
{
throw AccessEx;
}// catch
catch (Exception Ex)
{
throw Ex;
}// catch
}
private void ValidatingReader_ValidationEventHandler(object sender,
ValidationEventArgs args)
{
// 10- Implement your logic for each validation iteration
string strTemp;
strTemp = "Line: " + this.Reader.LineNumber + " - Position: " +
this.Reader.LinePosition + " - " + args.Message;
this.Results.Add(strTemp);
}