Validating XML using XMLValidatingReader


Level: Beginner

You can use XmlValidatingReader class to validate an cml file against an XSD schema, Here is the code snippet to do it,

XmlSchemaCollection schemaCol = new XmlSchemaCollection();
schemaCol.Add(“”,schemaFile);
XmlTextReader textReader = null;
XmlValidatingReader vReader = null;
try
{
textReader = new XmlTextReader(xmlFile);
// create a validating reader.
vReader = new XmlValidatingReader(textReader);
// validate using the schemas stored in the schema collection.
vReader.Schemas.Add (schemaCol);
// set the validation event handler
vReader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// read and validate the XML data.
while (vReader.Read()){}
}
catch (Exception ex)
{
return (false);
}
finally
{
// close the readers

vReader.Close ();
textReader.Close ();
}

 


And your Event Handler to handle the validation callbacks,

private void ValidationCallBack (object sender, ValidationEventArgs args)
{
this._xmlFeedValid = false;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s